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)