2015-05-18 152 views
1

因此,我试图通过SMTPlib与Python发送电子邮件,但是我无法使其工作。我读了微软的SMTP规范,并相应地把它们放进去,但我无法让它工作。这里是我的代码:通过SMTP发送电子邮件时遇到问题Python

# Send an email 
    SERVER = "smtp-mail.outlook.com" 
    PORT = 587 
    USER = "******@outlook.com" 
    PASS = "myPassWouldBeHere" 
    FROM = USER 
    TO  = ["******@gmail.com"] 
    SUBJECT = "Test" 
    MESSAGE = "Test" 
    message = """\ 
From: %s 
To: %s 
Subject: %s 
%s 
""" % (FROM, ", ".join(TO), SUBJECT, MESSAGE) 
    try: 
     server = smtplib.SMTP() 
     server.connect(SERVER, PORT) 
     server.starttls() 
     server.login(USER,PASS) 
     server.sendmail(FROM, TO, message) 
     server.quit() 
    except Exception as e: 
     print e 
     print "\nCouldn't connect." 

我从一个键盘记录的代码,但我清理了一下。我读了here关于基本SMTP的工作原理,但是有一些东西比如starttls(Methods)我不太明白。

我真的很感激任何帮助。

+0

“*我无法让它工作*”是什么意思?你有错误信息吗?它会让你的PC崩溃吗? –

回答

9

试试这个。这适用于Python 2.7。

def send_mail(recipient, subject, message): 

    import smtplib 
    from email.MIMEMultipart import MIMEMultipart 
    from email.MIMEText import MIMEText 

    username = "[email protected]" 
    password = "sender's password" 

    msg = MIMEMultipart() 
    msg['From'] = username 
    msg['To'] = recipient 
    msg['Subject'] = subject 
    msg.attach(MIMEText(message)) 

    try: 
     print('sending mail to ' + recipient + ' on ' + subject) 

     mailServer = smtplib.SMTP('smtp-mail.outlook.com', 587) 
     mailServer.ehlo() 
     mailServer.starttls() 
     mailServer.ehlo() 
     mailServer.login(username, password) 
     mailServer.sendmail(username, recipient, msg.as_string()) 
     mailServer.close() 

    except error as e: 
     print(str(e)) 


send_mail('[email protected]', 'Sent using Python', 'May the force be with you.') 
+0

如果消息只有一个部分,则将其封装在多部分中显然是多余的。 – tripleee

相关问题