Python脚本 - 发送电子邮件

时间:2015-07-13 07:32:24

标签: python email subprocess

我想知道“通过python脚本发送带附件的电子邮件的最佳方式是什么”? 我应该使用“ subprocess ”并使用此命令行

"mail -s "Test" email@googlemail.com < file.txt"

另一种选择是smtplib https://docs.python.org/2/library/email-examples.html

哪个选项更好?

2 个答案:

答案 0 :(得分:2)

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@email.com'
recipient = 'recipient@recipient.com'
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()

答案 1 :(得分:0)

yagmail(我是开发人员)的目的是让发送电子邮件变得非常简单,尤其是HTML或附件需求。

请尝试以下代码:

import yagmail
yag = yagmail.SMTP('email@email.com', 'password')
contents = ['See my attachment below', '/home/you/some_file.txt']
yag.send('recipient@recipient.com', subject = 'Subject', contents = contents)

请注意这里的魔力:contents是一个列表,其中将自动加载等于文件路径的项目,mimetype猜测并附加。

还涉及更多魔术,例如易于嵌入的图像,无密码脚本,无用户名脚本,简单别名,智能默认设置等等。我建议/鼓励您阅读github页面:-)。随意提出问题或添加功能请求!

您可以使用pip来安装yagmail:

pip install yagmail # Python 2
pip3 install yagmail # Python 3