python自动发邮件

注意:由于邮箱限制smtp、pop3协议的发送,所以使用发送邮箱时需开通smtp、pop3协议!

 

发送HTML格式的邮件

# -*-coding:utf-8-*-
import
smtplib from email.header import Header from email.mime.text import MIMEText # 连接的邮箱服务器 smtpserver = 'smtp.sina.com' # 登录 user = 'xxxx@sina.com' password = 'xxxx' # 由sender发送给receiver sender = 'xxxx@sina.com'
receiver = 'xxxx@qq.com'  # receiver可以是一个列表,这样就可以发送多个邮箱 # 发送主题 subject = 'Test first mail for HTML' # HTML内容 msg = MIMEText('<html><h1>你好<h1><html>','html','utf-8') msg['Subject'] = Header(subject,'utf-8') smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(user, password) smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit()

 

 

发送带附件的邮件

# -*-coding:utf-8-*-
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# 登录邮箱的信息
_user = "xxxx@sina.com"
_pwd  = "xxxx"
_to   = "xxxx@126.com"

#如名字所示Multipart就是分多个部分
msg = MIMEMultipart()
msg["Subject"] = "发送一个附件"
msg["From"]    = _user
msg["To"]      = _to

#---这是文字部分---
part = MIMEText("你好,这是附件")
msg.attach(part)

#---这是附件部分---
#任何类型的附件都可以
part = MIMEApplication(open('C:\\Users\\90658\\Desktop\\资料.txt','rb').read())
part.add_header('Content-Disposition', 'attachment', filename="资料.txt")
msg.attach(part)

smtp = smtplib.SMTP("smtp.sina.com", timeout=30)#连接smtp邮件服务器,端口默认是25
smtp.login(_user, _pwd)#登陆服务器
smtp.sendmail(_user, _to, msg.as_string())#发送邮件
smtp.close()

 

封装函数:

 1 from email.mime.text import MIMEText
 2 from email.header import Header
 3 import smtplib
 4 import os
 5 
 6 def send_mail(file_new):
 7     f = open(file_new,'rb')
 8     mail_body = f.read()
 9     f.close()
10 
11     msg = MIMEText(mail_body,'html','utf-8')
12     msg['Subject'] = Header("自动化测试报告",'utf-8')
13 
14     smtp = smtplib.SMTP()
15     smtp.connect("smtp.sina.com")
16     smtp.login("xxxx@sina.com","xxxxx")
17     smtp.sendmail("xxxxx@sina.com","xxxx@126.com",msg.as_string())
18     smtp.quit()
19     print("email has send out!")
发邮件函数

 

posted @ 2017-02-15 16:28  _HLP_huang  阅读(192)  评论(0)    收藏  举报