首页 > 解决方案 > 通过python脚本更改发件人邮件ID的显示名称

问题描述

import smtplib
import os

EMAIL_ADDRESS = abc@gmail.com
EMAIL_PASSWORD = os.environ.get('EMAIL_PASS')

with smtplib.SMTP('smtp.gmail.com',587) as smtp:
    smtp.ehlo()  #identifies ourselves with the mail server that we are using
    smtp.starttls() #to encrypt the traffic
    smtp.ehlo() #to re-identify ourselves as encrypted connection

    smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)

    subject = "Regarding your text role"
    body = "This is to inform u that ur text role has been updated"

    msg = f'Subject: {subject}\n\n{body}'

    smtp.sendmail('Random User <abc@gmail.com>','abcd@gmail.com', msg)

即使代码已成功执行,我在 abcd@gmail.com 中没有将显示名称显示为“随机用户”
可能是什么问题?

标签: pythonsmtplib

解决方案


您不想更改fromin smtp.sendmail(),但您想更改电子邮件内容本身。

msg = 'From: Random User <abc@gmail.com>\nTo: abcd@gmail.com\nSubject: subject\n\nbody'
smtp.sendmail('abc@gmail.com','abcd@gmail.com', msg)

推荐阅读