Python:电子邮件问题

时间:2010-07-27 19:08:06

标签: python email

我正在使用下面的脚本向自己发送电子邮件,脚本运行良好且没有错误,但我没有收到电子邮件。

import smtplib

sender = 'foo@hotmail.com'
receivers = ['foo@hotmail.com']

message = """From: From Person <foo@hotmail.com>
To: To Person <foo@hotmail.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"

修改

该脚本名为test.py

4 个答案:

答案 0 :(得分:5)

为什么使用localhost作为SMTP?

如果您使用的是Hotmail,则需要使用hotmail帐户,提供密码,输入端口和SMTP服务器等。

以下是您需要的一切: http://techblissonline.com/hotmail-pop3-and-smtp-settings/

编辑: 以下是使用gmail的示例:

def mail(to, subject, text):
    msg = MIMEMultipart()

    msg['From'] = gmail_user
    msg['To'] = to
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    part = MIMEBase('application', 'octet-stream')
    Encoders.encode_base64(part)
    msg.attach(part)

    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmail_user, gmail_pwd)
    mailServer.sendmail(gmail_user, to, msg.as_string())
    # Should be mailServer.quit(), but that crashes...
    mailServer.close()

答案 1 :(得分:2)

我有一些东西可以补充Klark的好答案。当我尝试:

Encoders.encode_base64(part)

我收到了错误

NameError: global name 'Encoders' is not defined

应该是

encoders.encode_base64(msg)

https://docs.python.org/2/library/email-examples.html

答案 2 :(得分:1)

去年四月杰夫阿特伍德的blog post可能会有所帮助。

答案 3 :(得分:0)

“localhost”SMTP服务器无法与Hotmail一起使用。您必须对密码进行硬编码,以便Hotmail也可以对您进行身份验证。 Hotmail的默认SMTP是端口25上的“smtp.live.com”。尝试:

import smtplib

sender = 'foo@hotmail.com'
receivers = ['foo@hotmail.com']
password = 'your email password'

message = """From: From Person <foo@hotmail.com>
To: To Person <foo@hotmail.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
   smtpObj = smtplib.SMTP("smtp.live.com",25)
   smtpObj.ehlo()
   smtpObj.starttls()
   smtpObj.ehlo()
   smtpObj.login(sender, password)
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"