附件在python中使用smptplib连接两次

时间:2015-06-09 08:37:44

标签: python smtplib

我正在尝试在python中实现我想要发送的功能 文件作为电子邮件警报的附件 一切正常。我收到了所需主题的电子邮件提醒,但唯一的问题是我在电子邮件提醒中两次获得相同的附件。

    fileMsg = email.mime.base.MIMEBase('application','octet-stream')
    fileMsg.set_payload(file('/home/bsingh/python_files/file_dict.txt').read())
    #email.encoders.encode_base64(fileMsg)
    fileMsg.add_header('Content-Disposition','attachment;filename=LogFile.txt')
    emailMsg.attach(fileMsg)

  # send email
    server = smtplib.SMTP(smtp_server)
    server.starttls()
    server.login(username, password)
    server.sendmail(from_add, to_addr,emailMsg.as_string())
    server.quit()

3 个答案:

答案 0 :(得分:5)

我自己一直遇到这个问题。我有'alternative'作为我的消息的MIMEMultipart类型。当我更改为默认值'mixed'时,副本消失了。

因此,如果您使用emailMsg创建了MIMEMultipart('alternative'),则可能会遇到同样的问题。

我相信'alternative'用于提供邮件正文的文本和html版本,因此如果您使用它,我认为除了附件之外,您还需要提供这两种版本。

我希望有所帮助。

我还没有找到任何好的解释;电子邮件可能变得非常复杂。

答案 1 :(得分:3)

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

请尝试以下代码:

import yagmail
yag = yagmail.SMTP(from_add, password)
contents = ['See my attachment below', '/home/bsingh/python_files/file_dict.txt']
yag.send(contents = contents)

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

还有更多魔术,例如易于嵌入图像,无密码脚本,无用户名脚本,简单别名,智能默认值(请注意我省略了tosubject参数?)等等。我建议/鼓励您阅读github页面:-)。随意提出问题或添加功能请求!

您可以使用pip来安装yagmail:

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

答案 2 :(得分:0)

版本有问题。已解决