gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:11:42 24 4
gpt4 key购买 nike

这是我的代码

# Import smtplib to provide email functions
import smtplib

# Import the email modules
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Define email addresses to use
addr_to = 'user@outlook.com'
addr_from = 'user@aol.com'

# Define SMTP email server details
smtp_server = 'smtp.aol.com'
smtp_user = 'user@aol.com'
smtp_pass = 'pass'

# Construct email
msg = MIMEMultipart('alternative')
msg['To'] = addr_to
msg['From'] = addr_from
msg['Subject'] = 'test test test!'

# Create the body of the message (a plain-text and an HTML version).
text = "This is a test message.\nText and html."
html = """\

"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via an SMTP server
s = smtplib.SMTP(smtp_server)
s.login(smtp_user,smtp_pass)
s.sendmail(addr_from, addr_to, msg.as_string())
s.quit()
我只希望收到的电子邮件在发件人电子邮件地址之前显示发件人姓名,如下所示: sender_name

最佳答案

在 2020 年和 Python 3 中,您可以执行以下操作:

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)

关于python - 如何在python电子邮件脚本中的发件人地址之前添加发件人姓名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46107983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com