簡體   English   中英

如何獲取從 smtplib 發送的 email 的 message-id

[英]how to get message-id of email sent from smtplib

我想記錄用戶對我郵件的回復並將其顯示為我的應用程序中的線程。 為此,我在 email 頭中使用了 message-id 的幫助。 當我發送郵件時,我可以看到屏幕上正在打印消息 ID 我如何獲取此消息 ID。 我創建的消息 ID 也被覆蓋。 我的代碼如下。

import smtplib
from email.mime.text import MIMEText

subject = 'Hello!'
message = 'hiii!!!'
email = 'someone@somewhere.com'
send_from = 'me@example.com'
msg = MIMEText(message, 'html', 'utf-8')
msg['Subject'] = subject
msg['From'] = send_from
msg['To'] = email
msg['Message-ID'] = '01234567890123456789abcdefghijklmnopqrstuvwxyz'
send_to = [email]

smtp_server = 'email-smtp.us-east-1.amazonaws.com'
smtp_port = 587
user_name = 'abcd'
password = 'abcd'
try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.set_debuglevel(True)
    server.starttls()
    server.ehlo()
    server.login(user_name,password)
    server.sendmail(send_from, send_to, msg.as_string())

except Exception, e:
    print e

使用email.utils.make_msgid創建符合RFC 2822的Message-ID標頭:

msg-id = [CFWS] "<" id-left "@" id-right ">" [CFWS]

我發現上面的答案令人難以置信的混亂。 希望以下內容對其他人有所幫助:

import smtplib
import email.message
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import email.utils as utils

def send_html_email(subject, msg_text,
                    toaddrs=['foo@gmail.com']):
    fromaddr = 'me@mydomain.com'

    msg = "\r\n".join([
        "From: " + fromaddr,
        "To: " + ",".join(toaddrs),
        "Subject: " + subject,
        "",
        msg_text
    ])

    msg = email.message.Message()
    msg['message-id'] = utils.make_msgid(domain='mydomain.com')
    msg['Subject'] = subject
    msg['From'] = fromaddr
    msg['To'] = ",".join(toaddrs)
    msg.add_header('Content-Type', 'text/html')
    msg.set_payload(msg_text)

    username = fromaddr
    password = 'MyGreatPassword'
    server = smtplib.SMTP('mail.mydomain.com',25)
    #server.ehlo() <- not required for my domain.
    server.starttls()
    server.login(username, password)
    server.sendmail(fromaddr, toaddrs, msg.as_string())
    server.quit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM