如何在Python中发送带有PDF附件的电子邮件?

16

我想编辑以下代码并发送带有附件的电子邮件。 附件是一个pdf文件,位于Linux环境下的/home/myuser/sample.pdf。 我应该如何更改以下内容?

可能是重复问题:
如何使用python发送电子邮件附件

import smtplib  
fromaddr = 'myemail@gmail.com'  
toaddrs  = 'youremail@gmail.com'  
msg = 'Hello'  


# Credentials (if needed)  
username = 'myemail'  
password = 'yyyyyy'  

# The actual mail send  
server = smtplib.SMTP('smtp.gmail.com:587')  
server.starttls()  
server.login(username,password)  
server.sendmail(fromaddr, toaddrs, msg)  
server.quit()  

3
现在几乎是一个问题了。您能解释一下为什么在谷歌搜索“smtplib attach file”的第一页结果中没有一个合适的吗? - Jon Clements
2
使用email模块,示例在http://docs.python.org/library/email-examples.html。 - Martijn Pieters
尝试一下这个教程email_attachments。正如其他答案所提到的那样,它也使用了MIME。 - NIlesh Sharma
2
在这里询问“smtplib attach file”问题有什么问题吗?为什么不能去谷歌搜索呢? - alwbtc
7
当你在谷歌搜索“smtplib attach file”时,这现在是排名靠前的搜索结果之一。 :-) - dan8394
显示剩余2条评论
2个回答

32

在这种情况下,您可以使用电子邮件包创建一条消息 -

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg.attach(MIMEText(open("/home/myuser/sample.pdf").read()))

然后发送消息。

import smtplib
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()

这里有几个例子 - http://docs.python.org/library/email-examples.html

更新

由于上面的链接返回了404错误,因此更新链接为https://docs.python.org/2/library/email-examples.html。感谢@Tshirtman


更新2:附加PDF的最简单方式

要附加pdf文件,请使用pdf标志:

def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
    ## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
    from socket import gethostname
    #import email
    from email.mime.application import MIMEApplication
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    import smtplib
    import json

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    with open(password_path) as f:
        config = json.load(f)
        server.login('me@gmail.com', config['password'])
        # Craft message (obj)
        msg = MIMEMultipart()

        message = f'{message}\nSend from Hostname: {gethostname()}'
        msg['Subject'] = subject
        msg['From'] = 'me@gmail.com'
        msg['To'] = destination
        # Insert the text to the msg going by e-mail
        msg.attach(MIMEText(message, "plain"))
        # Attach the pdf to the msg going by e-mail
        with open(path_to_pdf, "rb") as f:
            #attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf")
            attach = MIMEApplication(f.read(),_subtype="pdf")
        attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
        msg.attach(attach)
        # send msg
        server.send_message(msg)

致敬/鸣谢: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script


3
不确定此答案是否有所更改,但就我而言,适用于PDF的类型是 MIMEApplication - spalac24
9
你所提供的代码中,“file”是什么?它是Python函数吗? - Hamman Samuel
4
就 Python 3.7x 版本而言,现在可以这样导入 MIME* 类: from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart - user9074332
2
file 给出一个错误。这是什么? - Serdia
2
我投票-1,因为不清楚file()是什么。 - Arash
显示剩余8条评论

6

3
这个链接现在已经失效了。 - Tshirtman
如果我想发送一个 svg 文件怎么办? - Charlie Parker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接