python實例26[sendemail]
一 發(fā)送簡單的純文本郵件
import os.path
import smtplib
import email
def sendTextMail(mailhost,sender,recipients,ccto = '',bccto = '',subject = '',message = '', messagefile = ''):
try:
mailport=smtplib.SMTP(mailhost)
except:
sys.stderr.write('Unable to connect to SMTP host "' + mailhost \
+ '"!\nYou can try again later\n')
return 0
if(os.path.exists(messagefile) and os.path.isfile(messagefile)):
with open(messagefile,'r') as f:
message += f.read()
fullmessage = 'From: ' + ' <' + sender + '> \n' +\
'To: ' + recipients + '\n' +\
'CC: '+ ccto + '\n' +\
'Bcc: ' + bccto + '\n' +\
'Subject: ' + subject + '\n' +\
'Date: ' + email.Utils.formatdate() +'\n' +\
'\n' +\
message
try:
#mailport.set_debuglevel(1)
allrecipients = recipients.split(',')
if not ccto == '':
allrecipients.extend(ccto.split(','))
if not bccto == '':
allrecipients.extend(bccto.split(','))
#print allrecipients
#allrecipients must be list type
failed = mailport.sendmail(sender, allrecipients, fullmessage)
except Exception as e:
sys.stderr.write(repr(e))
return 0
finally:
mailport.quit()
return 1
注意:
recipients,ccto,bccto是接收者的郵件地址,多個地址間使用,分割;
message = '', messagefile = ''表示要發(fā)送的email的內(nèi)容,為可選參數(shù),messagefile表示email的內(nèi)容來自一個文本文件;
mailport.sendmail(sender, recipients, message)中,message中的from/to/bcc等只是用來email的顯示,真正的收件人必須通過recipients來傳入,recipients必須為收件人的email地址的數(shù)組,
二 發(fā)送html的郵件
import os.path
import smtplib
import email
from email import encoders
import mimetypes
from email.mime.base import MIMEBase
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def getMIMEObj(path):
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
msg = None
#print maintype
#print subtype
if maintype == 'text':
fp = open(path)
# Note: we should handle calculating the charset
msg = MIMEText(fp.read(), _subtype=subtype, _charset='utf-8')
fp.close()
elif maintype == 'image':
fp = open(path, 'rb')
msg = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'audio':
fp = open(path, 'rb')
msg = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(path, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
# Encode the payload using Base64
encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path))
return msg
def sendHtmlMail(mailhost,subject,sender,recipients,ccto = '',bccto = '',htmldir = '', htmlfile = ''):
try:
mailport=smtplib.SMTP(mailhost)
except:
sys.stderr.write('Unable to connect to SMTP host "' + mailhost \
+ '"!\nYou can try again later\n')
return 0
msgroot = MIMEMultipart('related')
msgroot['From'] = sender
msgroot['To'] = recipients
msgroot['Cc'] = ccto
msgroot['Bcc'] = bccto
msgroot['Subject'] = subject
msghtml = MIMEMultipart('alternative')
msgroot.attach(msghtml)
if os.path.exists(os.path.join(htmldir,htmlfile)):
htmlf = open(os.path.join(htmldir,htmlfile))
htmlmessage = MIMEText(htmlf.read(),'html','utf-8')
htmlf.close()
msghtml.attach(htmlmessage)
for root, subdirs, files in os.walk(htmldir):
for file in files:
if file == htmlfile:
continue
else:
msgroot.attach(getMIMEObj(os.path.join(root,file)))
failed = 0
try:
#mailport.set_debuglevel(1)
allrecipients = recipients.split(',')
if not ccto == '':
allrecipients.extend(ccto.split(','))
if not bccto == '':
allrecipients.extend(bccto.split(','))
#print allrecipients
failed = mailport.sendmail(sender, allrecipients, msgroot.as_string())
print failed
except Exception as e:
sys.stderr.write(repr(e))
finally:
mailport.quit()
return failed
注意:
htmldir參數(shù)表示要發(fā)送的html文件所在的目錄,此目錄下僅包含html文件和html文件引用的相關(guān)文件,且所有引用的文件必須與html都在同一目錄下,不能有子目錄;
htmlfile參數(shù)表示要顯示到email中的html文件;
例如:
有html文件如下:
d:\html
|--myhtmlemail.html
|--mylinkedtext.txt
|--myimage.gif
且myhtmlemail.html的內(nèi)容為:
<html>
<body>
<a href="mylinkedtext.txt">message1</a>
<br/>
<h1>This is HTML email sent by python</h1>
<img src="myimage.gif" alt="my message image" />
</body>
</html>
則收到的email如下:

三 使用如下:
mailhost = 'mail-relay.example.com'
sender = "AAA@example.com"
recipients = "BBB@example.com,EEE@example.com"
ccto = 'CCC@example.com'
bccto = 'DDD@example.com'
subject = "Testing1"
message = "Testing!\nTesting!\n"
messagefile = "mymessage.txt"
htmldir = 'D:\\html'
htmlfile = 'myhtmleamil.html'
sendTextMail(mailhost,sender,recipients,ccto,bccto,subject,message,messagefile)
sendHtmlMail(mailhost, subject,sender,recipients,htmldir=htmldir,htmlfile=htmlfile)
四 發(fā)送帶有附件的email
import os.path
import smtplib
import email
import mimetypes
from email import encoders
from email.mime.base import MIMEBase
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def getMIMEObj(path):
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
msg = None
#print maintype
#print subtype
if maintype == 'text':
fp = open(path)
# Note: we should handle calculating the charset
msg = MIMEText(fp.read(), _subtype=subtype, _charset='utf-8')
fp.close()
elif maintype == 'image':
fp = open(path, 'rb')
msg = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'audio':
fp = open(path, 'rb')
msg = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(path, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
# Encode the payload using Base64
encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path))
return msg
def sendMail(mailhost,subject,sender,recipients,ccto = '',bccto = '',message = '', payloads = ''):
try:
mailport=smtplib.SMTP(mailhost)
except:
sys.stderr.write('Unable to connect to SMTP host "' + mailhost \
+ '"!\nYou can try again later\n')
return 0
msgroot = MIMEMultipart('mixed')
msgroot['From'] = sender
msgroot['To'] = recipients
msgroot['Cc'] = ccto
msgroot['Bcc'] = bccto
msgroot['Subject'] = subject
alternative = MIMEMultipart('alternative')
msgroot.attach(alternative)
mes = MIMEText(message,'plain','utf-8')
alternative.attach(mes)
for file in payloads.split(','):
if os.path.isfile(file) and os.path.exists(file):
msgroot.attach(getMIMEObj(file))
else:
sys.stderr.write("The file %s cannot be found" % file)
try:
#mailport.set_debuglevel(1)
allrecipients = recipients.split(',')
if not ccto == '':
allrecipients.extend(ccto.split(','))
if not bccto == '':
allrecipients.extend(bccto.split(','))
#print allrecipients
failed = mailport.sendmail(sender, allrecipients, msgroot.as_string())
if failed == None:
sys.stderr.write(failed)
return 0
except Exception as e:
sys.stderr.write(repr(e))
return 0
finally:
mailport.quit()
return 1
mailhost = 'mail-relay.company.com'
sender = "AAA@Company.com"
recipients = "BBB@company.com"
ccto = 'CCC@company.com'
bccto = 'DDD@company.com'
subject = "Testing1"
message = "Testing!\nTesting!\n"
sendMail(mailhost,subject,sender,recipients,message = message,payloads = 'c:\\test\\test.ba,C:\\test\s7\\mytable.txt')
參考:
http://canofy.javaeye.com/blog/265600
http://docs.python.org/library/email-examples.html
http://www.rzrgm.cn/itech/archive/2011/02/18/1958114.html
完!


浙公網(wǎng)安備 33010602011771號