This article introduces how to send mails using python. This article introduces how to send mails using python.
# coding=utf-8
import smtplibfrom time import sleepfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipart
Def send_email (** param): ''' send email author: cdq: param: {"username": "", "password": "", "from_addr ": "", "to_addr": "", "smtpserver": "", "subject": "", "file_path": ""}: file_path = file path: return: '''error = "" flag = True try: # from conf_isms.adconf import local_host_ip if not param ['is _ send']: flag = False msg = MIMEMultipart () content = 'Hello:
'\' Data report has been sent to the mailbox. Please check
'\' Wish you a pleasant life! 'Body = MIMEText (content, _ subtype = "html", _ charset = "UTF-8") msg. attach (body) if isinstance (param ['File _ path'], list): for m in param ['File _ path']: att = MIMEText (open (m, 'RB '). read (), 'base64', 'utf-8') file_name = m. split ('/') [-1] att ["Content-Type"] = 'application/octet-stream' att ["Content-Disposition"] = 'attachment; filename = "% s" '% file_name.encode ('gbk') # prevent the download file name from garbled msg. attach (att) msg ['to'] = ';'. join (param ['to _ addr']) msg ['from'] = param ['from _ add'] msg ['subobject'] = param ['subobject'] sm = smtplib. SMTP (param ['smtpserver'], port = 25) # sm. set_debuglevel (1) sm. ehlo () sm. starttls () sm. ehlo () sm. login (param ['username'], param ['password']) sm. sendmail (param ['from _ addr '], param ['to _ addr'], msg. as_string () sleep (5) sm. quit () print "% s send successfully" % param ['File _ path'] flag = True random T Exception, ex: traceback. print_exc () print "send Failed" flag = False error = "error % s" % str (ex) finally: return flag, error
The above is the details about how to use python to send emails. For more information, see other related articles in the first PHP community!