欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python(email 邮件收发)

程序员文章站 2022-04-25 16:05:07
1、发送 html 文本内容的邮件 # smtplib 负责发送邮件 import smtplib # MIMEText 负责构造邮件内容 from email.mime.text import MIMEText # Header 是用来构建邮件头的 from email.header import ......

1、发送 html 文本内容的邮件

# smtplib 负责发送邮件
import smtplib
# mimetext 负责构造邮件内容
from email.mime.text import mimetext
# header 是用来构建邮件头的
from email.header import header

smtpserver= "smtp.163.com"
sender = "zhengying0813@163.com"
password = "mdzwninbzedkxxx"
receiver = "zhengying0813@163.com"
subject = "python email test"
# 三个参数:第一个为文本内容,第二个 html 设置文本格式,第三个 utf-8 设置编码
msg = mimetext("<html><h1>你好!</h1></html>","html","utf-8")
# 定义邮件主题
msg["subject"] = header(subject,"utf-8")
msg["from"] = header(sender,"utf-8")
msg["to"] = header(receiver)

smtp = smtplib.smtp()
smtp.connect(smtpserver)
# 登录 smtp 服务器
smtp.login(sender,password)
# msg.as_string() 把 mimetext 变成 str 对象
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()

 2、发送带附件的邮件

import smtplib
from email.mime.text import mimetext
from email.header import header
from email.mime.multipart import mimemultipart

smtpserver= "smtp.163.com"
sender = "zhengying0813@163.com"
password = "mdzwninbzedkcxxx"
receiver = "zhengying0813@163.com"
subject = "python email test"

# 创建一个带附件的实例
msg = mimemultipart()
msg["subject"] = header(subject,"utf-8")
msg["from"] = header(sender,"utf-8")
msg["to"] = header(receiver)

# log.txt 为报告文件
file = open("log.txt","rb").read()
att = mimetext(file,"base64","utf-8")
# 这里的 filename 定义邮件中显示什么名字
att["content-disposition"] = 'attachment; filename="log.txt"'
# 添加文件到邮件附件中去
msg.attach(att)

smtp = smtplib.smtp()
smtp.connect(smtpserver)
smtp.login(sender,password)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()