Copy codeThe Code is as follows:
Def sendmail (login ={}, mail = {}):
'''\
@ Param login ['user'] login ['passwd']
@ Param mail ['to _ addr'] mail ['subobject'] mail ['content'] mail ['Attach ']
'''
From datetime import datetime
From base64 import b64encode
Import smtplib, mimetypes
From email. mime. text import MIMEText
From email. mime. multipart import MIMEMultipart
From email. mime. image import MIMEImage
User_info = login ['user']. split ('@')
Mail_configure = {}
Mail_configure ['mail _ encoding'] = 'utf-8'
Mail_configure ['mail _ supplier '] = user_info [1]
Mail_configure ['from _ addr '] = login ['user']
Mail_configure ['server _ host'] = 'smtp. % s' % mail_configure ['mail _ supplier ']
Error = None
Try:
Email = MIMEMultipart ()
Email ['from'] = mail_configure ['from _ addr ']
Email ['to'] = mail ['to _ addr ']
Email ['subobject'] = '=? % S? B? % S? = '% (Mail_configure ['mail _ encoding'], b64encode (mail ['subobject'])
Email_content = MIMEText (mail ['content'], _ charset = mail_configure ['mail _ encoding'])
Email. attach (email_content)
If 'Attach 'in mail:
For I in mail ['Attach ']:
Ctype, encoding = mimetypes. guess_type (I)
If ctype is None or not encoding is None:
Ctype = 'application/octet-stream'
Maintype, subtype = ctype. split ('/', 1)
Att = MIMEImage (lambda f: (f. read (), f. close () (open (I, 'rb') [0], _ subtype = subtype)
Att. add_header ('content-disposition', 'attachment', filename = I)
Email. attach (att)
Smtp = smtplib. SMTP ()
Smtp. connect (mail_configure ['server _ host'])
Smtp. login (user_info [0], login ['passwd'])
Smtp. sendmail (mail_configure ['from _ addr '], mail ['to _ addr'], email. as_string ())
Smtp. quit ()
Failed t Exception as e:
Error = e
Return (mail_configure ['from _ addr '], mail [' to _ addr '], error)
Test
Copy codeThe Code is as follows:
Def t21 ():
Login = {
'User': 'ak43 @ sina.com ',
'Passwd': 'Hello @ d'
}
Mail = {
'To _ addr': 'ak32 @ sina.com; ak32@21cn.com ',
'Subobject': 'test email without attachments ',
'Content ':'''\
Sz002718, AIA ceiling
Sz002719, Michael
Sz002722, Golden Wheel Co., Ltd.
''',
}
Print sendmail (login, mail)
Login = {
'User': 'hellot @ sina.com ',
'Passwd': 'Hello # world'
}
Mail = {
'To _ addr': 'tom12 @ sina.com; tom12@21cn.com ',
'Subobject': 'test email with attachments ',
'Content ':'''\
Sz002718, AIA ceiling
Sz002719, Michael
Sz002722, Golden Wheel Co., Ltd.
''',
'Attach ': ['e:/a/a.txt']
}
Print sendmail (login, mail)