通过sendmail从python发送邮件

时间:2020-03-05 18:56:21  来源:igfitidea点击:

如果我不想通过SMTP而是通过sendmail发送邮件,是否有用于封装此过程的python库?

更好的是,是否有一个好的库可以抽象整个" sendmail -versussmtp"选择?

我将在大量的Unix主机上运行此脚本,其中只有一些在localhost:25上侦听;其中一些是嵌入式系统的一部分,不能设置为接受SMTP。

作为优良作法的一部分,我真的很想让库自己解决标头注入漏洞-因此,将字符串转储到popen('/ usr / bin / sendmail','w')会更近比我想要的金属。

如果答案是"去写一个库",那就去吧;-)

解决方案

回答

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

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

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

回答

最简单的答案是smtplib,我们可以在此处找到相关文档。

我们需要做的就是将本地sendmail配置为接受来自localhost的连接,默认情况下它可能已经这样做。当然,我们仍在使用SMTP进行传输,但是它是本地sendmail,与使用命令行工具基本相同。

回答

这是一个简单的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" % "[email protected]")
    p.write("To: %s\n" % "[email protected]")
    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

回答

标头注入不是发送邮件的方式,而是构建邮件的方式。检查电子邮件包,构造带有该邮件的邮件,对其进行序列化,然后使用子流程模块将其发送到/ 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"] = "[email protected]"
msg["To"] = "[email protected]"
msg["Subject"] = "This is the subject."
p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
p.communicate(msg.as_string())