本文的python发送邮件,使用的是SMTP协议,端口为25.
下面是完整的 代码片段
。
import smtplib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.utils import parseaddr, formataddr
class SendEmail():
_from_addr = None
_attachments = []
def __init__(self, smtp_server, port):
self.smtp = smtplib.SMTP(smtp_server, port)
self.smtp.set_debuglevel(1)
def _format_addr(self, s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
def login(self, user, password):
self._from_addr = user
self.smtp.login(user, password)
def add_file(self, file_name_list):
"""
添加附件
:param file_name_list: 附件地址列表
:return:
"""
file = MIMEMultipart()
for file_name in file_name_list:
with open(file_name, 'rb') as f:
attach_file_base = MIMEBase('application', 'octet-stream')
attach_file_base.set_payload(f.read())
attach_file_base.add_header('Content-Disposition', 'attachment',
filename=('utf-8', '', file_name.split("\\")[-1]))
encoders.encode_base64(attach_file_base)
file.attach(attach_file_base)
self._attachments.append(file)
def send_email(self, to_addr, send_word, from_nickname, to_nickname, header, type):
"""
发送email
:param to_addr: 接收方邮箱
:param from_nickname: 发送人昵称
:param to_nickname: 接收人昵称
:param send_word: 发送信息
:param header: 标语
:param type: 发送的信息格式(plain: text, html:html)
:return:
"""
# MIMEMultipart 可以组合发送HTML或者Plain,但是要指定subtype是alternative:
msg = MIMEMultipart('alternative')
# 邮件正文是 MIMEText
contents = MIMEText(send_word, type, _charset='utf-8')
# 发送人名字
msg['From'] = self._format_addr('{} <{}>'.format(from_nickname, self._from_addr))
# 接收人名字
msg['To'] = self._format_addr('{} <{}>'.format(to_nickname, to_addr))
# 邮件主题
msg['Subject'] = Header(header, 'utf-8').encode()
for data in self._attachments:
# 添加到MIMEMultipart
msg.attach(data)
msg.attach(contents)
try:
self.smtp.sendmail(self._from_addr, to_addr, msg.as_string())
except Exception as e:
print(e)
finally:
self.smtp.quit()
if __name__ == '__main__':
new_obj = SendEmail('smtp.qq.com', 25)
new_obj.login('258428@qq.com', '密码')
new_obj.add_file(['文件地址'])
new_obj.send_email(to_addr=['757098@qq.com'], send_word='CSDN', from_nickname="Dozt", to_nickname='Dozt', header="生活愉快", type='html')
密码是你进行smtp权限开通时的密码,不是邮箱登陆密码