通过身份验证在代理后面发送邮件

时间:2020-02-25 20:08:01

标签: python sendmail smtplib

我正在尝试从anoutlook帐户发送电子邮件,并从文件中读取联系人。

在没有代理的情况下进行测试没有问题,但是有了公司的代理,我得到了->

“ SMTPServerDisconnected(”连接意外关闭“) smtplib.SMTPServerDisconnected:连接意外关闭”

我使用smtplib和袜子进行代理设置。

此处是代码:

import socks

from string import Template

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

MY_ADDRESS = 'email@outlook.com'
PASSWORD = 'pass'




def get_contacts(filename):
    """
    Return two lists names, emails containing names and email addresses
    read from a file specified by filename.
    """

    names = []
    emails = []
    with open(filename, mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails

def read_template(filename):
    """
    Returns a Template object comprising the contents of the 
    file specified by filename.
    """

    with open(filename, 'r', encoding='utf-8') as template_file:
        template_file_content = template_file.read()
    return Template(template_file_content)

def main():
    names, emails = get_contacts('mycontacts.txt') # read contacts
    message_template = read_template('message.txt')
    print ("enviando mensaje")

    # set up the SMTP server
    socks.setdefaultproxy(socks.HTTP, 'proxy', port, True,'username', 'password')
    socks.wrapmodule(smtplib)

    s = smtplib.SMTP(host='smtp.office365.com', port=587)
    s.set_debuglevel(True)
    s.starttls()
    s.login(MY_ADDRESS, PASSWORD)


    # For each contact, send the email:
    for name, email in zip(names, emails):
        msg = MIMEMultipart()       # create a message

        # add in the actual person name to the message template
        message = message_template.substitute(PERSON_NAME=name.title())

        # Prints out the message body for our sake
        print(message)

        # setup the parameters of the message
        msg['From']=MY_ADDRESS
        msg['To']=email
        msg['Subject']="This is TEST"

        # add in the message body
        msg.attach(MIMEText(message, 'plain'))

        # send the message via the server set up earlier.
        s.send_message(msg)
        del msg

    # Terminate the SMTP session and close the connection
    s.quit()

if __name__ == '__main__':
    main()

有什么帮助吗?


已解决:

我将smtp连接的端口从587更改为25,并且可以使用!

1 个答案:

答案 0 :(得分:1)

在linux中,只要设置了http_proxy / https_proxy环境变量,就可以了。在Windows中,https://www.proxifier.com/将允许您通过代理正确发送所有流量。