Python sends SMTP emails with attachments

Source: Internet
Author: User

Python sends SMTP emails with attachments

Using the python email module, you can easily send emails. You can even attach attachments to the emails! The premise is that you have enabled the SMTP service in your mailbox (generally, it is enabled. If it is not enabled, you can set it in your mailbox ), you can write both the recipient and the sender as an email address for testing. In this way, you can send emails to yourself.

# Coding: utf-8import smtplibfrom email. mime. multipart import MIMEMultipart # python2.4 and earlier versions. MIMEMultipart. MIMEMultipart (), which is the same as from email. mime. text import MIMETextfrom email. mime. image import MIMEImagesender = '2017 @ qq.com '# sender address receiver = '2017 @ qq.com' # recipient address smtpserver = 'smtp .qq.com '# email server username = '2016' # username password = 'abcdefg' # Password smtp = smtplib. SMTP () def send_email (msg, file_name): msgRoot = MIMEMultipart ('related') msgRoot ['subobject'] = file_name # mail title, here, I set the title to msgText = MIMEText ('% s' % msg, 'html', 'utf-8 ') # The text you sent will be displayed in html format msgRoot. attach (msgText) att = MIMEText (open ('% s' % file_name, 'rb '). read (), 'base64', 'utf-8 ') # Add attachment att ["Content-Type"] = 'application/octet-stream' att ["Content-Disposition"] = 'attachment; filename = "% s" '% file_name msgRoot. attach (att) while 1: # try sending until sending is successful try: smtp. sendmail (sender, aggreger, msgRoot. as_string () # send the email break failed T: try: smtp. connect (smtpserver) # connect to the mail server smtp. login (username, password) # log on to the email server using T: print "failed to login to smtp server" # logon failure if _ name _ = "_ main __": MSG = "" # text FILE to be sent = "" # FILE to be sent send_email (MSG, FILE)




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.