#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Software : PyCharm
# @CreateTime: 2021-01-26 13:44
# @Author : pangdun_Fat
# @File : mail_module
# ref >>
# https://zhuanlan.zhihu.com/p/89868804
# https://www.jianshu.com/p/6e777bfb9ca1
# 先导入相关的库和方法
import smtplib, email
# 负责构造文本
from email.mime.text import MIMEText
# 负责将多个对象集合起来
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
from email.utils import formataddr, formatdate
from collections.abc import Iterable
from pathlib import Path
class class_email():
# def __init__(self):
# # 整理收件人列表
# self.mm_body_content = ''
# self.server = None
#
# # 设置邮箱域名、发件人邮箱、邮箱授权码、收件人邮箱
# # SMTP服务器,这里使用163邮箱
# # mail_host = "smtp.163.com"
# self.mail_server = ''
# # 发件人邮箱
# self.username = ''
# # 邮箱授权码,注意这里不是邮箱密码,如何获取邮箱授权码,请看本文最后教程
# self.password = ''
# # 收件人邮箱,可以为多个收件人
# self.to_mail = ''
# # 抄送人邮箱,可以为多个抄送人
# self.cc_mail = ''
# self.to_all_mail = '' # 包含收件人和抄送人,以 逗号 分割
def close(self):
if self.server:
self.server.quit()
# print("关闭SMTP对象")
else:
print("没有创建STMP对象")
def _format_mail(self, list_mail):
str_mail = ''
if isinstance(list_mail, str):
str_mail = list_mail
elif isinstance(list_mail, Iterable):
str_mail = ', '.join(list_mail)
else:
raise TypeError('recvivers is error!!!')
return str_mail
def _login_via_stmp(self):
assert self.username and self.password, 'email login information must is not missing !!!'
try:
# 创建SMTP对象
self.server = smtplib.SMTP()
# 设置发件人邮箱的域名和端口,端口地址为25
self.server.connect(self.mail_server, 25)
# set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息
# self.server.set_debuglevel(1)
self.server.set_debuglevel(0)
# 登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码
self.server.login(self.username, self.password)
print('user({}) login success!'.format(self.username))
except Exception as e:
print('login fail!\n{}\n'.format(e))
def __str__(self):
str_message = '''
this mail is
from {}
to {}
cc {}
'''.format(
self.username,
self.to_mail,
self.cc_mail
)
return str_message
def init(self, dict_mail_conf:dict):
'''
设置邮箱域名、发件人邮箱、邮箱授权码、收件人邮箱
:param dict_mail_conf:
:return:
'''
self.mail_server = dict_mail_conf['mail_server']
# 发件人邮箱
self.username = dict_mail_conf['username']
# 邮箱授权码,注意这里不是邮箱密码,如何获取邮箱授权码,请看本文最后教程
self.password = dict_mail_conf['password']
# 收件人邮箱,可以为多个收件人
to_mail = dict_mail_conf['to_mail']
cc_mail = dict_mail_conf['cc_mail']
self.to_all_mail = to_mail + cc_mail
self.to_mail = self._format_mail(to_mail)
self.cc_mail = self._format_mail(cc_mail)
print(str(self))
try:
# 构建 MIMEMultipart 对象代表邮件本身,可以往里面添加文本、图片、附件等
mail_msg = MIMEMultipart('related')
mail_msg["Accept-Language"] = "zh-CN" # 添加两个属性
mail_msg["Accept-Charset"] = "ISO-8859-1,utf-8"
# https://www.liaoxuefeng.com/wiki/897692888725344/923057144964288
mail_msg['From'] = formataddr((Header("媒资监控", 'utf-8').encode(), self.username))
mail_msg['To'] = formataddr((Header("管理员", 'utf-8').encode(), self.to_mail))
# mail_msg['Cc'] = self.cc_mail
# mail_msg['Date'] = formatdate(localtime=True)
self.mail_msg = mail_msg
except Exception as e:
print(e)
sys.exit(0)
def attachment(self, file_path='./csv/csv.xls', file_type='xls'):
assert self.mail_msg, 'must initialize MIMEMultipart befor adding attachment'
try:
with open(file_path, "rb") as attachment:
attach_file = MIMEApplication(attachment.read(), _subtype=file_type)
filename = Path(file_path).name
attach_file.add_header('Content-Disposition', "attachment", filename=filename)
self.mail_msg.attach(attach_file)
except Exception as e:
print(str(e))
sys.exit(0)
finally:
str_print = 'attach file: {}'.format(file_path)
print(str_print)
def send_mail(self, title='', body_content=''):
assert self.mail_msg, 'must initialize MIMEMultipart befor sending mail'
# body_content = str(self)
assert body_content, 'body_content must is not None!!!'
str_result = "email send success!!!"
try:
self._login_via_stmp()
# 构建 MIMEMultipart 对象代表邮件本身,可以往里面添加文本、图片、附件等
assert self.mail_msg, 'MIMEMultipart must not None'
# 设置邮件主题
self.mail_msg["Subject"] = Header(title, 'utf-8')
# 构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式
message_text = MIMEText(body_content, "html", "utf-8") # 执行utf-8编码
# 向MIMEMultipart对象中添加文本对象
self.mail_msg.attach(message_text)
self.mm_body_content = self.mail_msg.as_string()
assert self.mm_body_content, 'email body content must is not null !!!'
# # 发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为str
# self.server.sendmail(self.username, self.to_all_mail, self.mm_body_content)
self.server.sendmail(self.username, self.to_mail, self.mm_body_content)
except Exception as e:
print('\n\n{}\n\n'.format(e))
str_result = '\n{}'.format(e)
finally:
print(title)
print(get_curr_str_time_for_db(), str_result, '\n\n')
self.close()
from tools import *
if __name__ == '__main__':
dict_mail_conf = COLLECTION_MAIL_CONFIG.find_one({PRIMARY_KEY: MAIL_TEST})
if dict_mail_conf:
email = class_email()
email.init(dict_mail_conf)
with open('mail_test.txt', 'r', encoding='utf8') as f:
body_content = f.read()
if body_content:
title = 'C 语言教程-从公共邮箱邮箱到企业、QQ邮箱并抄送给163邮箱-{}'.format(get_curr_str_time_for_db())
title = '媒资监控邮件({})'.format(get_curr_str_time_for_db())
email.attachment()
# email.send_mail(title=title, body_content=body_content[:200])
python-email-邮件模板
最新推荐文章于 2023-08-18 15:34:48 发布
该博客介绍了一种使用Python实现邮件发送的方法,包括导入必要的库、构造邮件内容、设置SMTP服务器、登录邮箱以及添加附件等功能。示例代码详细展示了如何通过配置发件人、收件人信息来发送带有附件的邮件。
摘要由CSDN通过智能技术生成