本篇文章是在学习python之时所作的一点笔记: 简单的邮件发送功能
首先引入python的模块:
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header以下代码简单封装了一下发送邮件的函数:
def send_email(sender,receiver,subject,smtpserver,username,password,path,text,file_name): mime= MIMEMultipart() #创建MIMEMutipart mime['Subject'] = Header(subject, 'utf-8') #设置邮件标题 mime['From'] = sender #设置寄件人 mime['To'] = receiver #设置收件人 mt1= MIMEText(open(path, 'rb').read(), 'base64', 'gb2312') #添加附件 mt1["Content-Type"] = 'application/octet-stream' #二进制流数据 mt1["Content-Disposition"] = 'attachment; filename=%s'%file_name #这里的filename可以任意写,写什么名字,邮件中显示什么名字 mt2= MIMEText(text,'plain','gb2312') #邮件文本内容 mt2["Accept-Language"]="zh-CN" #支持语言 mime.attach(mt1) mime.attach(mt2) smtp = smtplib.SMTP() smtp.connect(smtpserver) #设置服务器 smtp.login(username, password) #登录 smtp.sendmail(sender, receiver, mime.as_string()) #发送邮件 smtp.quit()设置参数以及调用函数:
sender = 'xxx@126.com' #发件人邮箱 receiver = 'xxx@163.com' #收件人邮箱 subject = 'title' #标题 smtpserver = 'smtp.126.com' #服务器 如果发件使用qq邮箱则改为smtp.qq.com username = 'xxx' #用户名 password = 'xxx' #密码 path ='d:\\email.txt' #附件路径 file_name ='email.txt' #文件名 (可以自己设置文件名) text='This Text Is Great' #邮件文本内容 send_email(sender,receiver,subject,smtpserver,username,password,path,text,file_name)以上就是一个简单的邮件发送。
