使用SMTP从Python发送邮件

我正在使用以下方法使用SMTP从Python发送邮件。 这是正确的方法使用或有遗漏我缺less?

from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = "John Doe <john@doe.net>" to_addr = "foo@bar.com" subj = "hello" date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() 

我使用的脚本非常相似, 我在这里发布它作为如何使用电子邮件。*模块来生成MIME消息的例子; 所以这个脚本可以很容易地修改附加图片等

我依靠我的ISP来添加date时间标题。

我的ISP要求我使用安全的smtp连接发送邮件,我依赖于ssmtplib模块(可从http://www1.cs.columbia.edu/~db2501/ssmtplib.py下载);

和你的脚本一样,在SMTP服务器上用于validation的用户名和密码(下面给出的假值)在源文件中是纯文本的。 这是一个安全弱点; 但最好的select取决于你需要多么谨慎(想要?)来保护这些。

=======================================

 #! /usr/local/bin/python SMTPserver = 'smtp.att.yahoo.com' sender = 'me@my_email_domain.net' destination = ['recipient@her_email_domain.com'] USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER" PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER" # typical values for text_subtype are plain, html, xml text_subtype = 'plain' content="""\ Test message """ subject="Sent from Python" import sys import os import re from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL) # from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption) # old version # from email.MIMEText import MIMEText from email.mime.text import MIMEText try: msg = MIMEText(content, text_subtype) msg['Subject']= subject msg['From'] = sender # some SMTP servers will do this automatically, not all conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) try: conn.sendmail(sender, destination, msg.as_string()) finally: conn.quit() except Exception, exc: sys.exit( "mail failed; %s" % str(exc) ) # give a error message 

我通常使用的方法…没有太大的不同,但一点点

 import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText msg = MIMEMultipart() msg['From'] = 'me@gmail.com' msg['To'] = 'you@gmail.com' msg['Subject'] = 'simple email in python' message = 'here is the email' msg.attach(MIMEText(message)) mailserver = smtplib.SMTP('smtp.gmail.com',587) # identify ourselves to smtp gmail client mailserver.ehlo() # secure our email with tls encryption mailserver.starttls() # re-identify ourselves as an encrypted connection mailserver.ehlo() mailserver.login('me@gmail.com', 'mypassword') mailserver.sendmail('me@gmail.com','you@gmail.com',msg.as_string()) mailserver.quit() 

而已

另外,如果你想用TLS做smtpauthentication而不是SSL,那么你只需要改变端口(使用587)并且执行smtp.starttls()。 这对我工作:

 ... smtp.connect('YOUR.MAIL.SERVER', 587) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login('USERNAME@DOMAIN', 'PASSWORD') ... 

我看到的主要问题是,你没有处理任何错误:.login()和.sendmail()都有logging他们可以抛出的exception,似乎.connect()必须有一些方法来表明它是无法连接 – 可能是底层套接字代码抛出的exception。

确保你没有任何阻止SMTP的防火墙。 我第一次尝试发送电子邮件时,它被Windows防火墙和McAfee阻止 – 永远找不到它们。

那这个呢?

 import smtplib SERVER = "localhost" FROM = "sender@example.com" TO = ["user@example.com"] # must be a list SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." # Prepare actual message message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) # Send the mail server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit() 

以下代码对我来说工作正常:

 import smtplib to = 'mkyong2002@yahoo.com' gmail_user = 'mkyong2002@gmail.com' gmail_pwd = 'yourpassword' smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo() # extra characters to permit edit smtpserver.login(gmail_user, gmail_pwd) header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n' print header msg = header + '\n this is test msg from mkyong.com \n\n' smtpserver.sendmail(gmail_user, to, msg) print 'done!' smtpserver.quit() 

参考: http : //www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/

您应该确保以正确的格式 – RFC2822格式化date。

看到所有这些简单的答案? 请允许我通过几行完成所有的自我推销。

导入和连接:

 import yagmail yag = yagmail.SMTP('john@doe.net', host = 'YOUR.MAIL.SERVER', port = 26) 

那么这只是一个单线:

 yag.send('foo@bar.com', 'hello', 'Hello\nThis is a mail from your server\n\nBye\n') 

当它超出范围时它会实际closures(或者可以手动closures)。 此外,它将允许你在你的钥匙圈注册你的用户名,这样你就不必在你的脚本中写出你的密码(在写yagmail之前,真的让我困扰了!)

对于软件包/安装,提示和技巧请看git或pip ,可用于Python 2和Python 3。