How to send email attachments?

前端 未结 13 919
梦谈多话
梦谈多话 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:31

    Other answers are excellent, though I still wanted to share a different approach in case someone is looking for alternatives.

    Main difference here is that using this approach you can use HTML/CSS to format your message, so you can get creative and give some styling to your email. Though you aren't enforced to use HTML, you can also still use only plain text.

    Notice that this function accepts sending the email to multiple recipients and also allows to attach multiple files.

    I've only tried this on Python 2, but I think it should work fine on 3 as well:

    import os.path
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.application import MIMEApplication
    
    def send_email(subject, message, from_email, to_email=[], attachment=[]):
        """
        :param subject: email subject
        :param message: Body content of the email (string), can be HTML/CSS or plain text
        :param from_email: Email address from where the email is sent
        :param to_email: List of email recipients, example: ["a@a.com", "b@b.com"]
        :param attachment: List of attachments, exmaple: ["file1.txt", "file2.txt"]
        """
        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = from_email
        msg['To'] = ", ".join(to_email)
        msg.attach(MIMEText(message, 'html'))
    
        for f in attachment:
            with open(f, 'rb') as a_file:
                basename = os.path.basename(f)
                part = MIMEApplication(a_file.read(), Name=basename)
    
            part['Content-Disposition'] = 'attachment; filename="%s"' % basename
            msg.attach(part)
    
        email = smtplib.SMTP('your-smtp-host-name.com')
        email.sendmail(from_email, to_email, msg.as_string())
    

    I hope this helps! :-)

提交回复
热议问题