如何在python电子邮件脚本中在发件人地址之前添加发件人姓名

mra*_*ili 5 python email smtp

这是我的代码

    # 导入smtplib,提供email功能
    导入 smtplib

    # 导入邮件模块
    从 email.mime.multipart 导入 MIMEMultipart
    从 email.mime.text 导入 MIMEText

    # 定义要使用的电子邮件地址
    addr_to = 'user@outlook.com'
    addr_from = 'user@aol.com'

    # 定义 SMTP 电子邮件服务器详细信息
    smtp_server = 'smtp.aol.com'
    smtp_user = 'user@aol.com'
    smtp_pass = '通过'

    # 构造电子邮件
    msg = MIMEMultipart('替代')
    msg['To'] = addr_to
    msg['From'] = addr_from
    msg['Subject'] = '测试测试测试!'

    # 创建消息的正文(纯文本和 HTML 版本)。
    text = "这是一条测试消息。\n文本和 html。"
    html = """\

    """

    # 记录两个部分的 MIME 类型 - text/plain 和 text/html。
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')

    # 将部件附加到消息容器中。
    # 根据 RFC 2046,多部分消息的最后一部分,在这种情况下
    # HTML 消息,是最好的和首选的。
    msg.attach(part1)
    msg.attach(part2)

    # 通过 SMTP 服务器发送消息
    s = smtplib.SMTP(smtp_server)
    s.login(smtp_user,smtp_pass)
    s.sendmail(addr_from, addr_to, msg.as_string())
    退出()

我只希望收到的电子邮件在发件人电子邮件地址之前显示发件人姓名,如下所示:sender_name

mei*_*n99 9

这取决于“友好名称”是基本 ASCII 还是需要特殊字符。

基本示例:

msg['From'] = str(Header('Magnus Eisengrim <meisen99@gmail.com>'))
Run Code Online (Sandbox Code Playgroud)

如果您需要使用非 US-ASCII 字符,则比较复杂,但随附的文章应该会有所帮助,非常彻底:http : //blog.magiksys.net/generate-and-send-mail-with-python-tutorial


noa*_*myg 9

这是一个老问题 - 但是,我遇到了同样的问题并提出了以下问题:

msg['From'] = formataddr((str(Header('Someone Somewhere', 'utf-8')), 'xxxxx@gmail.com'))

您需要导入from email.header import Headerfrom email.utils import formataddr

这将使收件箱中仅显示发件人姓名,而不会显示<xxxxx@gmail.com>

虽然电子邮件正文将包含完整模式:

将发件人姓名和电子邮件放在一个字符串 ( Sender Name <sender@server.com>) 中会使一些电子邮件客户端在收件人的收件箱中相应地显示它(与第一张图片不同,只显示姓名)。

  • 很好的解决方案! (3认同)

小智 8

我采用了内置示例并用以下方法制作:

mail_body = "the email body"
mailing_list = ["user1@company.com"]
msg = MIMEText(mail_body)

me = 'John Cena <mail@company.com>'
you = mailing_list
msg['Subject'] = subject
msg['From'] = me
msg['To'] = mailing_list

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
Run Code Online (Sandbox Code Playgroud)


Dan*_*nin 7

In the year 2020 and Python 3, you do things like this:

from email.utils import formataddr
from email.message import EmailMessage
import smtplib

msg = EmailMessage()
msg['From'] = formataddr(('Example Sender Name', 'john@example.com'))
msg['To'] = formataddr(('Example Recipient Name', 'jack@example.org'))
msg.set_content('Lorem Ipsum')

with smtplib.SMTP('localhost') as s:
    s.send_message(msg)
Run Code Online (Sandbox Code Playgroud)