使用Python发送各种形式的邮件的方法汇总
我们平时需要使用Python发送各类邮件,这个需求怎么来实现?答案其实很简单,smtplib和email库可以帮忙实现这个需求。smtplib和email的组合可以用来发送各类邮件:普通文本,HTML形式,带附件,群发邮件,带图片的邮件等等。我们这里将会分几节把发送邮件功能解释完成。
smtplib是Python用来发送邮件的模块,email是用来处理邮件消息。
发送HTML形式的邮件
发送HTML形式的邮件,需要email.mime.text中的MIMEText的_subtype设置为html,并且_text的内容应该为HTML形式。
importsmtplib fromemail.mime.textimportMIMEText sender='***' receiver='***' subject='pythonemailtest' smtpserver='smtp.163.com' username='***' password='***' msg=MIMEText(u'''<pre> <h1>你好</h1> </pre>''','html','utf-8') msg['Subject']=subject smtp=smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username,password) smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit()
注意:这里的代码并没有把异常处理加入,需要读者自己处理异常。
发送带图片的邮件
发送带图片的邮件是利用email.mime.multipart的MIMEMultipart以及email.mime.image的MIMEImage:
importsmtplib
fromemail.mime.multipartimportMIMEMultipart
fromemail.mime.textimportMIMEText
fromemail.mime.imageimportMIMEImage
sender='***'
receiver='***'
subject='pythonemailtest'
smtpserver='smtp.163.com'
username='***'
password='***'
msgRoot=MIMEMultipart('related')
msgRoot['Subject']='testmessage'
msgText=MIMEText(
'''<b>Some<i>HTML</i>text</b>andanimage.<imgalt=""src="cid:image1"/>good!''','html','utf-8')
msgRoot.attach(msgText)
fp=open('/Users/1.jpg','rb')
msgImage=MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID','<image1>')
msgRoot.attach(msgImage)
smtp=smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username,password)
smtp.sendmail(sender,receiver,msgRoot.as_string())
smtp.quit()
发送带附件的邮件
发送带附件的邮件是利用email.mime.multipart的MIMEMultipart以及email.mime.image的MIMEImage,重点是构造邮件头信息:
importsmtplib
fromemail.mime.multipartimportMIMEMultipart
fromemail.mime.textimportMIMEText
sender='***'
receiver='***'
subject='pythonemailtest'
smtpserver='smtp.163.com'
username='***'
password='***'
msgRoot=MIMEMultipart('mixed')
msgRoot['Subject']='testmessage'
#构造附件
att=MIMEText(open('/Users/1.jpg','rb').read(),'base64','utf-8')
att["Content-Type"]='application/octet-stream'
att["Content-Disposition"]='attachment;filename="1.jpg"'
msgRoot.attach(att)
smtp=smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username,password)
smtp.sendmail(sender,receiver,msgRoot.as_string())
smtp.quit()