利用Python发送邮件
Python对SMTP支持有smtplib
和email
两个模块,email
负责构造邮件,smtplib
负责发送邮件。
首先要对邮箱进行设置,这里以QQ邮箱为例:
打开QQ邮箱后,选择“设置-账户”,找到“POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务”
开启pop3/smtp服务,并保存该授权码作为密码使用--生成授权码
最后代码如下:
# -*- coding:utf-8 -*- import smtplib from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import 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">这是一个链接</a></h2>‘,_subtype=‘html‘, _charset=‘utf-8‘) message.attach(message_text) # ==========================发送图片==================== def email_image(self,message): image_data = open(file="123456789.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=r"C:\Users\lenovo\Desktop\income.xlsx", mode="rb") message_file = MIMEText(_text=file_data.read(), _subtype="base64", _charset="utf-8") # 设置文件在附件当中的名字 message_file[‘Content-Disposition‘] = ‘attachment;filename="textfile.xlsx"‘ 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="eejjgbvxpzyadhhg") 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()
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16