! # / usr / bin / env Python
# - * - Coding: UTF-8 - * -
Import smtplib
from email.mime.multipart Import MimeMultipart
from email.mime.text Import MimeText
from email.utils Import parseaddr
from email.utils Import formataddr
from email.header Import Header
DEF __format_addr __ (addr):
# resolve e-mail addresses, postal order to ensure there is an alias can display
alias_name, parseaddr addr = (addr)
# prevent Chinese problem, transcode and format returns str
return formataddr ((Header (alias_name, charset = "UTF-. 8"). encode (),
addr.encode ( "UFT-. 8") IF the isinstance (addr, Unicode) the else addr))
DEF send_email_to (fromAdd, TOADD, Subject, html_text, filename = None):
SERVER = 'mail *** COM..'
the USER = '******'
= The PASSWD '***'
strFrom = __format_addr (fromAdd)
strto = list ()
# originally a pure mailbox list, now if it is a [ "jayzhen <[email protected]>"] format of the list to him
try :
for a tOADD in:
strTo.append (__ format_addr (a))
the except Exception AS E:
# toadd and for a no type judgment error on the direct reduction
strto = tOADD
msgRoot MimeMultipart = ( 'Related')
msgRoot.preamble = ' A Multi-Part IS the this message the MIME in the format. '
msgAlternative MimeMultipart = (' Alternative ')
msgRoot.attach (msgAlternative)
# mail object
msgtext = MimeText (html_text,' HTML ',' UTF-. 8 ')
msgRoot [' the subject '] = Header (subject) # This is the subject of the message, normalized by Header
msgRoot [ 'From'] = strFrom # Sender also been formatted
. msgRoot [ 'to'] = ',' join (strTo) # that it must be a str, or will be error "AttributeError: 'list' object NO attribute has 'the lstrip' "
msgAlternative.attach (msgtext)
SMTP = smtplib.SMTP (SERVER,. 11)
smtp.set_debuglevel (0)
# smtp.connect (SERVER)
smtp.login (the USER, the PASSWD)
# noted here that, the here fromadd and TOADD and msgRoot [ 'From'] msgRoot [ 'to'] distinction
smtp.sendmail (fromAdd, TOADD, msgRoot.as_string ())
smtp.quit ()
Original: https: //blog.csdn.net/u013948858/article/details/82903977