import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
from utils.common_logger import logger
class EmailSender:
def __init__(self, smtp_server='smtp的server地址'):
self.smtp_server = smtp_server
def send_mail(self, to, cc, subject, body, importance=None):
# 创建 MIMEText 对象
sender = '发送人邮箱'
message = MIMEText(body, "html", 'utf-8')
message['From'] = formataddr((str(Header('邮件标题', 'utf-8')), sender))
message['To'] = ", ".join(to)
message['Cc'] = ", ".join(cc)
message['Subject'] = Header(subject, 'utf-8')
# 如果配置了 importance,则设置邮件的重要性
if importance:
message['Importance'] = importance
# 合并收件人和抄送人列表
all_recipients = to + cc
try:
# 连接到 SMTP 服务器并发送邮件
smtp_obj = smtplib.SMTP(self.smtp_server)
smtp_obj.sendmail(sender, all_recipients, message.as_string())
print("Email sent successfully!")
except smtplib.SMTPException as e:
logger.error('邮件发送失败了,原因为:{}'.format(e))
def code_check_in_style(self, to, cc):
subject = '邮件标题'
body = """
<html>
<body>
书写你的邮件内容
</body>
</html>
"""
self.send_mail(to, cc, subject, body, importance='High')
# 使用示例
if __name__ == "__main__":
to = ['收件人邮箱']
cc = ['抄送人邮箱']
email_sender = EmailSender()
email_sender.code_check_in_style(to, cc)
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...