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

发布于 2021-01-29 17:50:36

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

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()
关注者
0
被浏览
143
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    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


    Update2:附加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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看