Python脚本 - 发送电子邮件
问题描述:
我想知道“通过python脚本发送带附件的电子邮件的最佳方式是什么”? 我应该用“子”,并借此命令行Python脚本 - 发送电子邮件
"mail -s "Test" [email protected] < file.txt"
另一种选择是https://docs.python.org/2/library/email-examples.html的smtplib?
哪个选项更好?
答
Python将是更灵活的发送电子邮件的方式。而且,正如你已经使用Python,将是最明智的。不需要使用子进程来调用外部脚本(这可能是不安全的)。
您可以附加更多不同类型的文件,更好地控制机构的内容。如果你想要的话,你可以把它变成一个通用的函数或类,可以给文本和文件名,收件人等
如果你有一个像上面这样的类,你可以将它导入到其他程序中,它可以用于调试或者发生错误时发送标志(或者有趣的事情发生)。
我倾向于用它来通知我运行一些自动化过程的健康状况。
另外@hiroprotagonist提到 - 这将使脚本平*立。
从你链接的文档此略有精简下来的例子是你真正需要知道:
# Import smtplib for the actual sending function
import smtplib
# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Subject'
me = '[email protected]'
recipient = '[email protected]'
msg['From'] = me
msg['To'] = recipient
# Assume we know that the image files are all in PNG format
for file in pngfiles:
# Open the files in binary mode. Let the MIMEImage class automatically
# guess the specific image type.
fp = open(file, 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)
# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, recipient, msg.as_string())
s.quit()
答
的yagmail全部目的(我开发者)是使其很容易发送电子邮件特别是在HTML或附件需求方面。
请尝试以下代码:
import yagmail
yag = yagmail.SMTP('[email protected]', 'password')
contents = ['See my attachment below', '/home/you/some_file.txt']
yag.send('[email protected]', subject = 'Subject', contents = contents)
通知神奇在这里:contents
是一个列表,在这里等于文件路径的项目会自动加载,MIME类型猜到了,和连接。
还有更多的魔法参与,比如容易嵌入图片,无密码脚本,无用户脚本,简单的别名,智能默认等等。我建议/鼓励你阅读它的github页面:-)。随意提出问题或添加功能请求!
您可以通过使用PIP安装它得到yagmail:
pip install yagmail # Python 2
pip3 install yagmail # Python 3
我建议你使用库(的smtplib)。这样您的脚本将独立于您运行它的平台运行。 –
您的命令将读取要从'file.txt'发送的电子邮件。没有迹象表明它会发送带有附件的电子邮件。 – jfs
相关:[如何发送电子邮件附件与python](http://*.com/q/3362600/4279) – jfs