发送带有附件的电子邮件

时间:2020-02-03 16:50:34

标签: python python-3.x email

我正在尝试编写一个函数,用于发送带有附件的电子邮件。目前,它发送电子邮件但没有附件。有人可以评论吗?

    msg = MIMEMultipart()

    msg['From'] = my email

    msg['To'] = client email address

    msg['Subject'] = subject

    body = content

    msg.attach(MIMEText(body, 'plain'))
    ##### Load the address of the file which should be attached*********************************     
    filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("Text 
    files","*.txt"),("all files","*.*")))     

    Myfile = open(filename)

    attachment = MIMEText(Myfile.read())
    attachment.add_header('Content-Disposition', 'attachment', filename=filename)           


    msg.attach(attachment)
    mail = smtplib.SMTP('smtp.gmail.com', 587)
    msg = f'Subject: {subject}\n\n{content}'
    mail.ehlo()
    mail.starttls()
    mail.login('My email address', 'password')
    mail.sendmail('client email', My email address, msg)
    mail.close()

提前谢谢大家

1 个答案:

答案 0 :(得分:0)

首先,如我的评论中所述,您在此处覆盖msg

msg = f'Subject: {subject}\n\n{content}'

这时,用于指向的MIMEMultipart对象msg被销毁,您将仅发送该新字符串。难怪为什么没有附件:该字符串显然没有附件。

现在,您确实应该使用email模块的新API,如in the documentation所示。但是由于您已经在使用旧版API(例如MIMEMultipart类),所以需要将msg转换为字符串,如here所示:

# This is copied straight from the last link

msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

...

part1 = MIMEText(text, 'plain')  # example attachment

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)

mail.sendmail(
    me, you,
    msg.as_string()  # CONVERT TO STRING
)