如果我不想通过SMTP发送邮件,而是通过sendmail发送邮件,是否有一个用于封装此过程的python库?
更好的是,是否有一个好的库可以抽象出整个'sendmail -versus-smtp'的选择?
我将在一堆unix主机上运行这个脚本,其中只有一些正在监听localhost:25;其中一些是嵌入式系统的一部分,无法设置为接受SMTP。
作为良好实践的一部分,我真的希望让库自己处理标题注入漏洞 - 所以只需将字符串转储到popen('/usr/bin/sendmail', 'w')
就比我想要的更接近金属了
如果答案是'去写一个库',那就这样吧了! - )
答案 0 :(得分:114)
标头注入不是您发送邮件的一个因素,它是您构建邮件的一个因素。检查email包,用它构建邮件,将其序列化,然后使用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())
答案 1 :(得分:32)
这是一个简单的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
答案 2 :(得分:3)
使用os.popen
从Python使用sendmail命令是很常见的就个人而言,对于我自己不写的脚本,我认为只使用SMTP协议更好,因为它不需要安装说sendmail克隆在Windows上运行。
答案 3 :(得分:3)
这个问题很老,但值得注意的是,有一个消息构建和电子邮件传递系统名为Marrow Mailer(以前是TurboMail),在此消息被提出之前就已经可用了。
现在它被移植到支持Python 3并作为Marrow套件的一部分进行了更新。
答案 4 :(得分:3)
Python 3.5 + 版本:
import subprocess
from email.message import EmailMessage
def sendEmail(from_addr, to_addrs, msg_subject, msg_body):
msg = EmailMessage()
msg.set_content(msg_body)
msg['From'] = from_addr
msg['To'] = to_addrs
msg['Subject'] = msg_subject
sendmail_location = "/usr/sbin/sendmail"
subprocess.run([sendmail_location, "-t", "-oi"], input=msg.as_bytes())
答案 5 :(得分:-3)
我只是在寻找相同的东西,并在Python网站上找到了一个很好的例子: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以接受" localhost"上的连接。默认情况下,这适用于我的Mac,Ubuntu和Redhat服务器,但您可能需要仔细检查是否遇到任何问题。
答案 6 :(得分:-6)
最简单的答案是smtplib,您可以在其上找到文档here。
您需要做的就是将本地sendmail配置为接受来自localhost的连接,默认情况下可能已经这样做了。当然,您仍然使用SMTP进行传输,但它是本地sendmail,这与使用命令行工具基本相同。