[英]How can I get email.utils.make_msgid to pick from address domain instead of local hostname in Python
I am trying to get the message-id to pick the domain portion of the from address and not sure how to do it.我正在尝试获取消息 ID 以选择来自地址的域部分,但不知道该怎么做。 I can hardcode it but I would like it pick up whatever the domain portion of the from address我可以对其进行硬编码,但我希望它获取来自地址的任何域部分
message = MIMEMultipart("alternative")
message['From'] = email.utils.formataddr(('User1', 'aniga@domain.com')) # header address
message['Date'] = email.utils.formatdate(timeval=None, localtime=False, usegmt=False)
message['Message-ID'] = email.utils.make_msgid("".join(random.choice("0123456789ABCDEF") for i in range(16)), domain=pickfrom from address domain
message['Subject'] = 'Testing from Python'
message['To'] = email.utils.formataddr((recpient, recpient@example.com))
There is no built-in support for doing that;没有内置支持这样做; if you want to extract the domain part from the From:
address, you have to do that separately.如果要从From:
地址中提取域部分,则必须单独进行。
There should be no need for you to pick the idstring
yourself, by the way;顺便说一句,您应该不需要自己选择idstring
; let Python take care of that.让 Python 来处理。
You'll probably also want to upgrade to use the Python 3.6+ updated EmailMessage
API for new code.您可能还想升级以使用 Python 3.6+ 更新的EmailMessage
API 获取新代码。
from email.message import EmailMessage
import email.utils
message = EmailMessage()
message['From'] = email.utils.formataddr(('User1', 'aniga@domain.com'))
message['Date'] = email.utils.formatdate(timeval=None, localtime=False, usegmt=False)
# Notice change here
message['Message-ID'] = email.utils.make_msgid(domain=message['From'].groups[0].addresses[0].domain)
message['Subject'] = 'Testing from Python'
# Trivial typo + syntax edit here
message['To'] = email.utils.formataddr(('recipient', 'recipient@example.com'))
If what you have isn't a formataddr
it won't have a groups
attribute;如果你所拥有的不是formataddr
它就没有groups
属性; if you simply have a str
containing the sender's address, a quick and dirty heuristic is to simply split on @
and take everything up through the first >
or whitespace character as probably the domain name.如果你只是有一个包含发件人地址的str
,一个快速而肮脏的启发式方法是简单地拆分@
并通过第一个>
或空格字符将所有内容作为可能的域名。 But this has a number of pesky corner cases you really want to avoid - it's better to parse the From:
header (again, if necessary) and be reasonably sure that you really get it properly parsed.但这有一些你真的想避免的讨厌的极端情况 - 最好解析From:
header (再次,如果需要),并合理地确定你真的得到了正确的解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.