Python电子邮件"来自名称"定制

时间:2016-05-16 13:46:10

标签: python pyramid

我有一个python脚本来发送电子邮件,它工作正常,但问题是当我检查我的电子邮件收件箱。 enter image description here

我希望该用户名是自定义用户名而不是整个电子邮件地址。

enter image description here

3 个答案:

答案 0 :(得分:1)

您应该使用来自发件人地址的格式为:

Your Name <username@domain.com>

答案 1 :(得分:0)

我在https://en.wikibooks.org/wiki/Python_Programming/Email

获得了此代码
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
fromaddr = "youremailid@gmail.com"
toaddr = "target@example.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = ""
body = "This is just a test email. Do not reply to this"
msg.attach(MIMEText(body, 'plain'))
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login("youremailusername", "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)

来自地址的格式为
username@server.com
地址格式为
username@server.com 并且smtplib.SMTP接受0或2个参数。 第一个参数是类型str,第二个参数是类型int

答案 2 :(得分:0)

如果您正在使用多部分消息并呈现 Markdown,如果您想要漂亮的消息。

image


from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

multipart_msg = MIMEMultipart("alternative")

multipart_msg["Subject"] = message.splitlines()[0]
multipart_msg["From"] = DISPLAY_NAME + f' <{SENDER_EMAIL}>'
multipart_msg["To"] = receiver

text = message
html = markdown.markdown(text)

part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")

multipart_msg.attach(part1)
multipart_msg.attach(part2)

server.sendmail(SENDER_EMAIL, receiver,
                            multipart_msg.as_string())