我使用以下代码从localhost中的python程序发送电子邮件,
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = "tonyr1291@gmail.com"
you = "testaccount@gmail.com"
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
s = smtplib.SMTP('localhost',5000)
s.sendmail(me, you, msg.as_string())
s.quit()
此代码来自python文档。
当我运行此代码时,它会持续运行但不会发送电子邮件。
我想知道,我必须在除此代码之外的任何其他地方进行其他配置。
我没有看到任何错误。
我正在使用python 2.7
答案 0 :(得分:0)
您似乎正在使用gmail ID。现在,SMTP服务器不是您的龙卷风服务器。它是电子邮件提供商的服务器。
您可以在线搜索gmail服务器的smtp设置并获取以下内容:
我是从http://email.about.com/od/accessinggmail/f/Gmail_SMTP_Settings.htm
获得的此外,您需要确保在执行此操作时不启用gmail的2步验证,否则将失败。此外,gmail特别要求您发送其他内容,如ehlo和starttls。您可以在此处找到一个完整示例的上一个答案:How to send an email with Gmail as provider using Python?
import smtplib
gmail_user = user
gmail_pwd = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"