带有附件的电子邮件,发件人显示名称(或电子邮件)中带有变音符号

Email with Attachment with Umlaut in sender displayname (or email)

提问人:Erbs 提问时间:8/4/2023 更新时间:8/7/2023 访问量:52

问:

我正在尝试通过 python 发送带有附件的电子邮件,但是当显示名称(或电子邮件)包含德语变音符号“äöü”时,我从发送服务器收到错误,指出电子邮件不符合 RFC 5321/5322。没有一个,邮件发送工作正常。 我检查了其他几个问题,但他们的问题不在发件人中或没有发送附件,因此这些解决方案不适用于我的情况。

最小的工作示例(好吧,不起作用,但如果您从“displayname”中删除“ö”,则可以工作;login/passwort 丢失并且由于明显的原因更改了电子邮件地址),我在 Windows 上使用 python 3.11:

import smtplib
import ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

message = MIMEMultipart()
message.set_charset('utf-8')
subject = 'Support-Nr. 1'
message["Subject"] = subject
body = 'testmail 123 äöüß'
message.attach(MIMEText(body, "plain"))
filename = 'VCARD_A & B.vcf'
with open(filename, "rb") as attachment:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)
message.attach(part)
sender_email = '[email protected]'
receiver_email = '[email protected]'
displayname = 'Höhne'
message["From"] = displayname + '<' + sender_email + '>'
message["To"] = receiver_email
smtplogin = #loginname
smtppassword = #passwort
smtpserver = 'smtp.ionos.de'
smtpport = 465
context = ssl._create_unverified_context()
with smtplib.SMTP_SSL(smtpserver, smtpport, context=context) as server:
    server.login(smtplogin, smtppassword)
    server.sendmail(sender_email, receiver_email, message.as_string())

python-3.x utf-8 电子邮件附件

评论

0赞 JosefZ 8/5/2023
或?当然,需要...message["From"] = quopri.encodestring( displayname.encode('utf-8')) + '<' + sender_email + '>'import quopri
0赞 Erbs 8/7/2023
@JosefZ没有,要么有连接字符串和字节的错误,要么(如果我对整个字符串进行编码)server.sendmail 上还有另一个“字节没有方法编码”错误,因此尝试对其进行编码而不是在 UTF-8 中?idk的

答:

1赞 Erbs 8/7/2023 #1

对于其他寻找解决方案的人,我在 python 文档上找到了一个有效的示例。

import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg['Subject'] = 'Support-Nr. 1'
sender_email = '[email protected]'
receiver_email = '[email protected]'
displayname = 'Höhne'
msg['From'] = displayname + '<' + sender_email + '>'
msg['To'] = receiver_email
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
with open('VCARD_A & B.vcf', 'rb') as fp:
    img_data = fp.read()
    file_name = fp.name
msg.add_attachment(img_data, maintype='application', subtype='octet-stream', filename=file_name)
body = 'test123 äöüß'
msg.attach(MIMEText(body, "plain"))
smtplogin = #loginname
smtppassword = #password
smtpserver = 'smtp.ionos.de'
smtpport = 465
context = ssl._create_unverified_context()
with smtplib.SMTP_SSL(smtpserver, smtpport, context=context) as s:
    s.login(smtplogin, smtppassword)
    s.send_message(msg)