python 发送邮件实例
文件形式的邮件
#!/usr/bin/env python3
#coding: utf-8
import smtplib
from emailmimetext import MIMEText
from emailheader import Header
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtpcom'
username = '***'
password = '***'
msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8',单字节字符不需要
msg['Subject'] = Header(subject, 'utf-8')
smtp = smtplibSMTP()
smtpconnect('smtpcom')
smtplogin(username, password)
smtpsendmail(sender, receiver, msgas_string())
smtpquit()
HTML形式的邮件
#!/usr/bin/env python3
#coding: utf-8
import smtplib
from emailmimetext import MIMEText
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtpcom'
username = '***'
password = '***'
msg = MIMEText('
你好
','html','utf-8')msg['Subject'] = subject
smtp = smtplibSMTP()
smtpconnect('smtpcom')
smtplogin(username, password)
smtpsendmail(sender, receiver, msgas_string())
smtpquit()
带图片的HTML邮件
#!/usr/bin/env python3
#coding: utf-8
import smtplib
from emailmimemultipart import MIMEMultipart
from emailmimetext import MIMEText
from emailmimeimage import MIMEImage
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtpcom'
username = '***'
password = '***'
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgText = MIMEText('Some HTML text and an image
good!','html','utf-8')
msgRootattach(msgText)
fp = open('h:pythonjpg', 'rb')
msgImage = MIMEImage(fpread())
fpclose()
msgImageadd_header('Content-ID', '')
msgRootattach(msgImage)
smtp = smtplibSMTP()
smtpconnect('smtpcom')
smtplogin(username, password)
smtpsendmail(sender, receiver, msgRootas_string())
smtpquit()
带附件的邮件
#!/usr/bin/env python3
#coding: utf-8
import smtplib
from emailmimemultipart import MIMEMultipart
from emailmimetext import MIMEText
from emailmimeimage import MIMEImage
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtpcom'
username = '***'
password = '***'
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
#构造附件
att = MIMEText(open('h:pythonjpg', 'rb')read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="jpg"'