使用Python脚本发送邮件
作者:互联网
使用Python脚本发送邮件
一、准备工作
1、开启邮箱的IMAP/SMTP服务
获取POP3授权码(此处以网易邮箱为例介绍)
设置->POP3/SMTP/IMAP->开启IMAP/SMTP服务,并记录授权码(只显示一次,请务必记下)
2. 安装所需模块,采用pip安装
pip install email
#如果安装速度慢可以指定下载源
pip install email -i https://pypi.tuna.tsinghua.edu.cn/simple/
二、代码介绍
1、导入模块
导入所需的模块。
需要到os模块调取文件
使用smtp协议导入smtplib模块
与发送邮件相关的email模块
import os
import smtplib
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
2、定义发送邮件的基本信息
class Mail(object):
"""发送邮件类"""
def __init__(self, receiver,subject):
self.smtpServer = 'smtp.163.com' ## 邮箱的服务器
self.fromAddress = "********@163.com" ## 发件人邮箱账号
self.passWord = "*********" ## 此处为第一步获取的授权码
self.toAddressList = receiver
self.subject = subject
self.msg = self.__format_header()
3、格式化发送的邮件头
def __format_header(self):
msg = MIMEMultipart()
name = self.fromAddress.split('@')[0]
msg['From'] = formataddr((Header(name, 'utf-8').encode(), self.fromAddress))
msg['To'] = ",".join(self.toAddressList)
msg['Subject'] = Header(self.subject, 'utf-8').encode()
return msg
4、添加正文
def text(self, message):
"""添加普通文本"""
self.msg = self.__format_header()
self.msg.attach(MIMEText('{}'.format(message), 'plain', 'utf-8'))
def html(self, html):
"""添加html"""
self.msg = self.__format_header()
self.msg.attach(MIMEText('{}'.format(html), 'html', 'utf-8'))
5、添加附件
def attach_file(self, message, filelist):
"""添加附件"""
self.msg = self.__format_header()
self.msg.attach(MIMEText(message, 'plain', 'utf-8'))
for filename in filelist:
if os.path.isfile(filename):
filename = os.path.abspath(filename)
print("当前需要发送的文件:{}".format(filename))
try:
with open(filename, 'rb') as f:
mime = MIMEBase('file', 'xls', filename=filename)
mime.add_header('Content-Disposition', 'attachment', filename=filename)
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
mime.set_payload(f.read())
encoders.encode_base64(mime)
self.msg.attach(mime)
except Exception as e:
print("{}读取失败{}".format(filename, repr(e)))
6、发送邮件
def sent(self):
"""
发送信息
:return:
"""
try:
server = smtplib.SMTP(host=self.smtpServer, port=25)
server.login(self.fromAddress, self.passWord)
server.sendmail(self.fromAddress, self.toAddressList, self.msg.as_string())
server.quit()
except Exception as e:
print("发送邮件失败,错误原因:{}".format(repr(e)))
三、使用示例
1、类的实例化
实例化发送邮件的类,定义邮件的主题和收件人列表
message = Mail(to_list, subject)
2、添加正文和附件
添加邮件的正文和附件,调用Mail类的text和attach_file方法
message.text(string)
message.attach_file(filelist)
3、发送
发送邮件,调用Mail类的sent方法
message.sent
标签:format,Python,self,filename,发送,mime,msg,email,邮件 来源: https://www.cnblogs.com/Sunny-King/p/Python-sent_email.html