从python通过sendmail发送邮件

如果我不想通过SMTP发送邮件,而是通过sendmail发送邮件,是否有一个封装了这个过程的python库?

更好的是,有没有一个好的图书馆能够抽象出整个“sendmail -versus-smtp”的select?

我将在一堆unix主机上运行这个脚本,其中只有一些正在监听localhost:25; 其中一些是embedded式系统的一部分,不能设置为接受SMTP。

作为良好实践的一部分,我真的希望图书馆自己处理标题注入漏洞 – 所以只是倾倒一个stringpopen('/usr/bin/sendmail', 'w')是更接近比我想要的金属。

如果答案是“去写一个图书馆”,那就这样吧;-)

标题注入不是发送邮件的方式,这是构build邮件的一个因素。 检查电子邮件包,用它构build邮件,将其序列化,并使用subprocess模块将其发送到/usr/sbin/sendmail

 from email.mime.text import MIMEText from subprocess import Popen, PIPE msg = MIMEText("Here is the body of my message") msg["From"] = "me@example.com" msg["To"] = "you@example.com" msg["Subject"] = "This is the subject." p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE) p.communicate(msg.as_string()) 

这是一个简单的python函数,它使用unix sendmail发送邮件。

 def sendMail(): sendmail_location = "/usr/sbin/sendmail" # sendmail location p = os.popen("%s -t" % sendmail_location, "w") p.write("From: %s\n" % "from@somewhere.com") p.write("To: %s\n" % "to@somewhereelse.com") p.write("Subject: thesubject\n") p.write("\n") # blank line separating headers from body p.write("body of the mail") status = p.close() if status != 0: print "Sendmail exit status", status 

在Python 3.4中,Jim的回答对我没有帮助。 我不得不添加一个额外的universal_newlines=True参数subrocess.Popen()

 from email.mime.text import MIMEText from subprocess import Popen, PIPE msg = MIMEText("Here is the body of my message") msg["From"] = "me@example.com" msg["To"] = "you@example.com" msg["Subject"] = "This is the subject." p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE, universal_newlines=True) p.communicate(msg.as_string()) 

没有universal_newlines=True我明白了

 TypeError: 'str' does not support the buffer interface 

这个问题很古老,但值得注意的是,有一个消息构造和电子邮件传送系统,称为TurboMail ,在此消息被询问之前已经可用。

它现在被移植到支持Python 3并作为Marrow套件的一部分进行更新。

使用os.popen从Python中使用sendmail命令是很常见的

就个人而言,对于我自己写的脚本,我认为只是使用SMTP协议更好,因为它不需要安装sendmail克隆来在Windows上运行。

https://docs.python.org/library/smtplib.html

我只是在四处search,并在Python网站上find了一个很好的例子: http : //docs.python.org/2/library/email-examples.html

从提到的网站:

 # Import smtplib for the actual sending function import smtplib # Import the email modules we'll need from email.mime.text import MIMEText # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. fp = open(textfile, 'rb') # Create a text/plain message msg = MIMEText(fp.read()) fp.close() # me == the sender's email address # you == the recipient's email address msg['Subject'] = 'The contents of %s' % textfile msg['From'] = me msg['To'] = you # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('localhost') s.sendmail(me, [you], msg.as_string()) s.quit() 

请注意,这需要您正确设置sendmail / mailx才能接受“本地主机”上的连接。 这在我的Mac,Ubuntu和Redhat服务器默认情况下,但你可能要仔细检查,如果你遇到任何问题。

最简单的答案是smtplib,你可以在这里find文档。

所有你需要做的就是configuration你的本地sendmail接受来自本地主机的连接,这可能在默认情况下已经完成。 当然,您仍然使用SMTP进行传输,但是它是本地的sendmail,与使用命令行工具基本相同。