如何在python程序中发邮件
1个回答
展开全部
提供以下两种方式:
利用smtplib,email库
coding:utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import sys
reload(sys)
sys.setdefaultencoding("utf8")
# 配置收发件人
recvaddress = ['receiveemail@sina.com','receiveemail@qq.com']
# 163的用户名和密码
sendaddr_name = 'your_email@163.com'
sendaddr_pswd = 'your_password'
class SendMail:
def __init__(self,recver=None):
"""接收邮件的人:list or tuple"""
if recver is None:
self.sendTo = recvaddress
else:
self.sendTo = recver
def send(self,sub,content,attachcontent):
"""发送邮件"""
self.msg = MIMEMultipart()
#设置发送邮件
self.msg['from'] = sendaddr_name
try:
#设置邮箱服务器
smtp = smtplib.SMTP('smtp.163.com',25)
#登录
smtp.login(sendaddr_name,sendaddr_pswd)
#设置发送主题
self.msg['Subject'] = sub
#设置邮件内容
self.msg.attach(MIMEText(content))
#设置邮件附件,将附件的内容attachcontent,写到filename的文件中,作为附件发送
att1 = MIMEText(attachcontent, 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="testattach.txt"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字
self.msg.attach(att1)
#发送邮件
smtp.sendmail(self.msg['from'], self.sendTo, self.msg.as_string())
smtp.close()
print(u"发送邮件成功")
except Exception,e:
print(u'发送邮件失败:'+str(e))
raise
#调用
s = SendMail()
subject = "主题"
content = "这里是邮件内容"
attachcontent = "这里是附件哦"
s.send(subject,content,attachcontent)
2.利用webpy自带的email模块
首先要安装web.py的依赖库
pip install web.py
#coding:utf-8
import web
##### email服务器配置 #####
web.config.smtp_server = 'smtp.sina.com'
web.config.smtp_port = 25
web.config.smtp_username = '你的email前缀,@前的字符串'
web.config.smtp_password = '你的密码'
web.config.smtp_starttls = True
send_from="youremail@sina.com"
receiveemailaddr = ["receiveemail@qq.com","receiveemail@163.com"]
subject=u'这里是主题'
message=u'这里是邮件的内容'
def sendemail(sendfrom,sendto,subject,message,cc=None, bcc=None,headers=({'User-Agent': 'webpy.sendmail', 'X-Mailer': 'webpy.sendmail',})):
try:
web.sendmail(send_from,sendto,subject,message,cc=cc,bcc=bcc)
print "邮件发送成功"
except Exception,e:
print(str(e))
#调用
sendemail(send_from,receiveemailaddr,subject,message)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询