python发送邮件,以QQ邮箱为例
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
# smtplib模块负责连接服务器和发送邮件
# MIMEText:定义邮件的文字数据
# MIMEImage:定义邮件的图片数据
# MIMEMultipart:负责将文字图片音频组装子一起添加附件
class Send_email():
def __init__(self):
self.Host = "smtp.qq.com" #qq邮箱的服务地址
self.Subject = input("请输入邮件标题:") #设置邮件标题
self.From = input("请输入发件人地址:") #设置发件人邮箱
self.To = input("请输入收件人地址:") #设置收件人邮箱
# ==========================发送文本====================
def email_text(self,message ):
message_text = MIMEText(_text='<h2 style = "color:red;font-size:100px"><a href="http://www.baidu.com">这是网址</h2>')
message.attach(message_text)
# ==========================发送图片====================
def email_image(self,message):
image_data = open(file="D:\下载\2032946.jpg",mode="rb")
message_image = MIMEImage(_imagedata=image_data.read(),_subtype="base64",_charset ="utf-8")
# 设置发送邮件图片的名字
message_image["Content-disposition"] = 'attachment;filename = "text.jpg"'
image_data.close()
message.attach(message_image)
# ==========================发送附件====================
def email_file(self,message):
file_data = open(file="C:\Users\37461\Desktop\新建 XLS 工作表.xls",mode="rb")
message_file = MIMEText(_text=file_data.read(),_subtype="base64",_charset="utf-8")
# 设置发送邮件附件的名字
message_file["Content-Disposition"] = 'attachment;filename = "textfile.xls"'
file_data.close()
message.attach(message_file)
# ==========================发送邮件====================
def init_email(self):
message["From"]= self.From #设置邮件发件人
message["To"] = self.To #设置邮件接收人
message["Subject"] = self.Subject #设置邮件标题
# 获取简单邮件传输协议证书
email_client = smtplib.SMTP_SSL(host="smtp.qq.com")
# 设置发件人邮箱的域名和端口
email_client.connect(host="smtp.qq.com",port="465")
# 登陆邮件,权限验证,password为邮箱密码
result = email_client.login(user=self.From,password="ohuwivaostufbhei")
print("登录结果",result)
# 发送邮件,from_addr:发送人,to_addrs:收件人 ,msg:发送的文本
email_client.sendmail(from_addr=self.From,to_addrs=self.To,msg=message.as_string())
# 关闭邮件客户端
email_client.close()
if __name__== "__main__":
# 创建一个邮件对象
message = MIMEMultipart()
# 调用
email = Send_email()
email.email_text(message)
email.email_image(message)
email.email_file(message)
email.init_email()