Copy Code code as follows:
def sendmail (login={},mail={}):
'''\
@param login login[' user '] login[' passwd '
@param mail mail[' to_addr '] mail[' subject '] 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[' subject '] = ' =?%s? b?%s?= '% (mail_configure[' mail_encoding '],b64encode (mail[' subject '))
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 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 ()
Except Exception as E:
Error = E
Return (mail_configure[' from_addr '], mail[' to_addr '], error)
Test
Copy Code code as follows:
Def t21 ():
Login = {
' User ': ' ak43@sina.com ',
' passwd ': ' Hello@d '
}
Mail = {
' To_addr ': ' ak32@sina.com;ak32@21cn.com ',
' Subject ': ' Test mail without attachment ',
' Content ': '
sz002718, AIA Ceiling
sz002719, Max.
sz002722, Golden Wheel shares
''',
}
Print sendmail (login, mail)
Login = {
' User ': ' hellot@sina.com ',
' passwd ': ' Hello#world '
}
Mail = {
' To_addr ': ' tom12@sina.com;tom12@21cn.com ',
' Subject ': ' Test mail with Attachments ',
' Content ': '
sz002718, AIA Ceiling
sz002719, Max.
sz002722, Golden Wheel shares
''',
' Attach ': [' e:/a/a.txt ']
}
Print sendmail (login, mail)