欢迎来到代码驿站!

当前位置:首页 >

如何利用python发送邮件

时间:2020-09-26 18:00:26|栏目:|点击:

一、zmial发送邮件

zmial是第三方库,需进行安装

pip install zmail

完成后,来给发一封邮件

subject:标题
content_text:内容

 import zmail
 server = zmail.server('发件人邮箱地址','授权码')
 
 server.send_mail('收件人邮箱地址',{'subject':'Hello!','content_text':'By zmail.'})

二、smtplib发送邮件

import smtplib
from email.mime.text import MIMEText
#--------发件相关参数--------
smtpserver="smtp.qq.com"  #连接服务器
port = 465           #端口
sender = "741841851@qq.com"#账号
psw = "xxxxx"#密码 授权码
receiver="741841851@qq.com"#接收人

#--------编辑邮件内容--------

subject="qq邮件主题"
body= '<p>这个是发送的qq邮件</p>'
msg = MIMEText(body,'html','utf-8')
msg['from']=sender
msg['to']='741841851@qq.com'
msg['subject']=subject

#-----------test_email-------
smtp = smtplib.SMTP_SSL(smtpserver,port)#连接服务器
smtp.login(sender,psw)#登录
smtp.sendmail(sender,receiver,msg.as_string())#发送邮件
smtp.quit()

三、发送带附件的邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os

smtpserver='smtp.qq.com'
port =465
sender='741841851@qq.com'
psw = 'xxxx'
recevier = "741841851@qq.com"

filenamepath = os.path.join(os.path.dirname(os.path.realpath(__file__)),'ceshi.html')

with open(filenamepath,'rb') as f:
  mail_body=f.read().decode('utf-8')

msg = MIMEMultipart()
msg['from']=sender#发件人
msg['to']=recevier#收件人
msg['subject']='这是我的主题99'#主题

# 正文
body = MIMEText(mail_body,'html','utf-8')
msg.attach(body)
#附件
att = MIMEText(mail_body,'base64','gbk')#用utf-8会出现乱码
att['Content-Type']='application/octet-stream'
att['Content-Disposition']='attachment;filename="test_report.html"'
msg.attach(att)

####发送邮件
try:
  smtp = smtplib.SMTP()
  smtp.connect(smtpserver)#连接服务器
  smtp.login(sender,psw)#登录
except:
  smtp = smtplib.SMTP_SSL(smtpserver,port)
  smtp.login(sender,psw)#登录

smtp.sendmail(sender,recevier,msg.as_string())#发送邮件
smtp.quit()

上一篇:浅谈springmvc 通过异常增强返回给客户端统一格式

栏    目:

下一篇:R语言ggplot2边框背景去除的实现

本文标题:如何利用python发送邮件

本文地址:http://www.codeinn.net/misctech/5476.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有