侧边栏壁纸
博主头像
三味的小站 博主等级

世界上没有偶然,有的只是必然的结果。

  • 累计撰写 63 篇文章
  • 累计创建 14 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

smtplib发邮件发件人乱码问题

三味线
2023-04-11 / 0 评论 / 0 点赞 / 23 阅读 / 0 字

常规的发邮件代码如下:

import smtplib
from typing import Dict, List, Any
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.header import Header
import traceback
def send_email(
    title: str, content: str, receivers: List[str], content_type: str = "plain"
):
    """content_type: plain/html"""
    conf = SETTINGS.email_conf
    host = conf.get("host")
    port = conf.get("port")
    from_email = conf.get("email")
    from_name = conf.get("name")
    password = conf.get("password")
    ssl = conf.get("ssl")
    auth = conf.get("auth")
    if not host:
        return False
    try:
        smtp = smtplib.SMTP_SSL(host, port) if ssl else smtplib.SMTP(host, port)
        # if ssl:
        #    smtp.starttls()
        smtp.ehlo()
        if auth:
            smtp.login(from_email, password)
        message = MIMEMultipart()
        message["Subject"] = Header(title, "utf-8")
        message["From"] = f"{from_name} <{from_email}>"
        message["To"] = ",".join(receivers)
        message.attach(MIMEText(content, content_type, "utf-8"))
        smtp.sendmail(from_email, receivers, message.as_string())
        smtp.quit()
    except Exception as e:
        traceback.print_exc()
        return False
    return True

但是部分客户端(如Outlook)的发件人会显示乱码,如下:

From需做如下修改:

from email.utils import formataddr
message["From"] = formataddr((str(Header(from_name, "utf-8")), from_email))

可以在邮箱客户端查看邮件头,修改前后的From字段变化如下:

From: =?utf-8?q?XXXXX=3Cszspc=40xxxx=2Ecom=3E?=
From: =?utf-8?b?5Lic6aKG5pm66IO9?= <xxxx@xxx.com>

https://stackoverflow.com/questions/44385652/add-senders-name-in-the-from-field-of-the-email-in-python

0

评论区