How to send email attachments?

前端 未结 13 853
梦谈多话
梦谈多话 2020-11-22 01:14

I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the smtplib. Could someone please e

相关标签:
13条回答
  • 2020-11-22 01:32

    You can also specify the type of attachment you want in your e-mail, as an example I used 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)
    

    inspirations/credits to: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script

    0 讨论(0)
  • 2020-11-22 01:36

    The simplest code I could get to is:

    #for attachment email
    from django.core.mail import EmailMessage
    
        def attachment_email(request):
                email = EmailMessage(
                'Hello', #subject
                'Body goes here', #body
                'MyEmail@MyEmail.com', #from
                ['SendTo@SendTo.com'], #to
                ['bcc@example.com'], #bcc
                reply_to=['other@example.com'],
                headers={'Message-ID': 'foo'},
                )
    
                email.attach_file('/my/path/file')
                email.send()
    

    It was based on the official Django documentation

    0 讨论(0)
  • 2020-11-22 01:39

    Here's another:

    import smtplib
    from os.path import basename
    from email.mime.application import MIMEApplication
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.utils import COMMASPACE, formatdate
    
    
    def send_mail(send_from, send_to, subject, text, files=None,
                  server="127.0.0.1"):
        assert isinstance(send_to, list)
    
        msg = MIMEMultipart()
        msg['From'] = send_from
        msg['To'] = COMMASPACE.join(send_to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
    
        msg.attach(MIMEText(text))
    
        for f in files or []:
            with open(f, "rb") as fil:
                part = MIMEApplication(
                    fil.read(),
                    Name=basename(f)
                )
            # After the file is closed
            part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
            msg.attach(part)
    
    
        smtp = smtplib.SMTP(server)
        smtp.sendmail(send_from, send_to, msg.as_string())
        smtp.close()
    

    It's much the same as the first example... But it should be easier to drop in.

    0 讨论(0)
  • 2020-11-22 01:41
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    import smtplib
    import mimetypes
    import email.mime.application
    
    smtp_ssl_host = 'smtp.gmail.com'  # smtp.mail.yahoo.com
    smtp_ssl_port = 465
    s = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
    s.login(email_user, email_pass)
    
    
    msg = MIMEMultipart()
    msg['Subject'] = 'I have a picture'
    msg['From'] = email_user
    msg['To'] = email_user
    
    txt = MIMEText('I just bought a new camera.')
    msg.attach(txt)
    
    filename = 'introduction-to-algorithms-3rd-edition-sep-2010.pdf' #path to file
    fo=open(filename,'rb')
    attach = email.mime.application.MIMEApplication(fo.read(),_subtype="pdf")
    fo.close()
    attach.add_header('Content-Disposition','attachment',filename=filename)
    msg.attach(attach)
    s.send_message(msg)
    s.quit()
    

    For explanation, you can use this link it explains properly https://medium.com/@sdoshi579/to-send-an-email-along-with-attachment-using-smtp-7852e77623

    0 讨论(0)
  • 2020-11-22 01:44

    This is the code I ended up using:

    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email import Encoders
    
    
    SUBJECT = "Email Data"
    
    msg = MIMEMultipart()
    msg['Subject'] = SUBJECT 
    msg['From'] = self.EMAIL_FROM
    msg['To'] = ', '.join(self.EMAIL_TO)
    
    part = MIMEBase('application', "octet-stream")
    part.set_payload(open("text.txt", "rb").read())
    Encoders.encode_base64(part)
        
    part.add_header('Content-Disposition', 'attachment; filename="text.txt"')
    
    msg.attach(part)
    
    server = smtplib.SMTP(self.EMAIL_SERVER)
    server.sendmail(self.EMAIL_FROM, self.EMAIL_TO, msg.as_string())
    

    Code is much the same as Oli's post.

    Code based from Binary file email attachment problem post.

    0 讨论(0)
  • 2020-11-22 01:48

    With my code you can send email attachments using gmail you will need to:

    set your gmail address at "YOUR SMTP EMAIL HERE"

    set your gmail account password at "YOUR SMTP PASSWORD HERE_"

    In the ___EMAIL TO RECEIVE THE MESSAGE_ part you need to set the destination email address.

    Alarm notification is the subject,

    Someone has entered the room, picture attached is the body

    ["/home/pi/webcam.jpg"] is an image attachment.

    #!/usr/bin/env python
    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email.Utils import COMMASPACE, formatdate
    from email import Encoders
    import os
    
    USERNAME = "___YOUR SMTP EMAIL HERE___"
    PASSWORD = "__YOUR SMTP PASSWORD HERE___"
    
    def sendMail(to, subject, text, files=[]):
        assert type(to)==list
        assert type(files)==list
    
        msg = MIMEMultipart()
        msg['From'] = USERNAME
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
    
        msg.attach( MIMEText(text) )
    
        for file in files:
            part = MIMEBase('application', "octet-stream")
            part.set_payload( open(file,"rb").read() )
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"'
                           % os.path.basename(file))
            msg.attach(part)
    
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo_or_helo_if_needed()
        server.starttls()
        server.ehlo_or_helo_if_needed()
        server.login(USERNAME,PASSWORD)
        server.sendmail(USERNAME, to, msg.as_string())
        server.quit()
    
    sendMail( ["___EMAIL TO RECEIVE THE MESSAGE__"],
            "Alarm notification",
            "Someone has entered the room, picture attached",
            ["/home/pi/webcam.jpg"] )
    
    0 讨论(0)
提交回复
热议问题