Python自动发送邮件-smtplib和email库

一、先导入smtplib模块 导入MIMEText库用来做纯文本的邮件模板
二、发邮件几个相关的参数,每个邮箱的发件服务器不一样,以163为例子百度搜索服务器是 smtp.163.com
三、写邮件主题和正文,这里的正文是HTML格式的
四、最后调用SMTP发件服务

126mail -> qqmail send email

import uuid
import smtplib
from email.mime.text import MIMEText

#发邮件相关参数
smtpsever = 'smtp.126.com'
sender = '123@126.com'
psw = "XXX"              #126邮箱授权码
receiver = '456@qq.com'

#编辑邮件的内容
# subject=u"NBA"
body=str(uuid.uuid4())
msg=MIMEText(body,'html','utf-8')
msg['from']='123@126.com'
msg['to']='456@qq.com'
# msg['subject']=subject

try:
    smtp = smtplib.SMTP()
    smtp.connect(smtpsever)
    smtp.login(sender,psw)
    smtp.sendmail(sender,receiver,msg.as_string())
    print ("邮件发送成功")
except smtplib.SMTPException:
    print ("Error: 无法发送邮件")

qqmail->126mail send email

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import smtplib,uuid
from email.mime.text import MIMEText

#发邮件相关参数
smtpsever='smtp.qq.com'
sender='123@qq.com'
psw="XXXXX"            #qq邮箱授权码
receiver='456@qq.com'
port=465


#编辑邮件内容
subject = u"你猜这是啥?"
body = str(uuid.uuid4())
msg=MIMEText(body,'html','utf-8')
msg['from']='123@qq.com'
msg['to']='456@qq.com'
msg['subject'] = subject

#链接服务器发送
smtp = smtplib.SMTP_SSL(smtpsever,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

#发邮件相关参数
smtpsever='smtp.qq.com'
sender='123@qq.com'
#psw="xxxx"            #126邮箱授权码
psw="xxxx"
receiver='456789@qq.com'
port=465

filepath="E:\\result.html"  #编辑邮件的内容
with open(filepath,'rb') as fp:    #读文件
    mail_body=fp.read()

#主题
msg=MIMEMultipart()
msg["from"]=sender
msg["to"]=receiver
msg["subject"]=u"这个我的主题"

#正文
body=MIMEText(mail_body,"html","utf-8")
msg.attach(body)
att = MIMEText(mail_body,"base64","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(smtpsever)                     #连接服务器
    smtp.login(sender,psw)
except:
    smtp=smtplib.SMTP_SSL(smtpsever,port)
    smtp.login(sender,psw)  #登录
smtp.sendmail(sender,receiver,msg.as_string())  #发送
smtp.quit()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值