Starting from a partial duplication of work on the existing work of the release, took two weeks to debug the completely may be able to roar to see the realization of the target code, as the title says, this code the main user with the attachment of e-mail sent;
For code everyone only need to modify the next file path, e-mail address can be run, my side is mainly combined with NAVICAT data export + This send mail code, make timed tasks, so that the program executes on time every day, we do not need to guide the data every day, so that the program can be completed, Not a word how to say: Lazy people automation people are more lazy to think how to make the automation of the status quo is often not a lot of ideas
Say so much nonsense, directly to everyone to see the following code:
# Encoding:utf-8
Import Smtplib
From datetime import datetime
Import OS
From Email.mime.multipart import Mimemultipart
From Email.mime.text import Mimetext
From Email.mime.image import Mimeimage
HOST = ' smtp.163.com '
SUBJECT = U ' title content '
to = ' [email protected],[email protected] ' #收件人邮箱
from = ' [email protected] ' #发件人邮箱
msg = Mimemultipart (' related ')
msgtext= mimetext ("<font> Hello,<br> data See accessories, please find! </font> "," html "," Utf-8 ")
Msg.attach (Msgtext)
# Create a Mimetext object, attach, xlsx document
#file_name = Os.path.join (' xxxx ', ' mail.txt ')
Time = Datetime.today (). Strftime ('%y-%m-%d ')
# file_name = '/home/test/db_%s.sql '% datetime.today (). Strftime ('%y-%m-%d ')
Attach = Mimetext (open ('/home/test/db_%s.sql '% time, ' RB '). Read (), ' base64 ', ' Utf-8 ')
attach[' content-type '] = ' application/octet-stream '
attach[' content-disposition ' = (U ' attachment; filename= "Db_%s.sql" '% Time '). Encode (' Utf-8 ')
Msg.attach (Attach)
msg[' Subject '] = Subject
msg[' from ') = from
msg[' to ') = To
Try
Server = Smtplib. SMTP ()
Server.connect (HOST, ' 25 ')
# SERVER.STARTTLS ()
Server.login (' Login email address ', ' Authorization Code ')
Server.sendmail (From, To.split (', '), msg.as_string ())
Server.quit ()
Print (U ' mail sent successfully!) ‘)
Except Exception, E:
print ' failed ' + str (e)
Written in such a complete code, the intermediate process is not easy, but also want to provide help to the people in need
Copyright notice: This article by the author original, without permission not reproduced if there are problems can contact me for consultation, qq:996551709 notes: Blog Park
Python SMTP send with Attachment email