質問

I want to record users reply to my mail and display it as thread in my application. For this purpose I am using help of message-id in present in the email head. When I sent a mail I can see message-id being printed on the screen how do i get this message-id. Also the message-id created by me is overrided. my code is as below.

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
役に立ちましたか?

解決

Use email.utils.make_msgid to create RFC 2822-compliant Message-ID header:

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

他のヒント

I found the above answer to be incredibly confusing. Hopefully the below helps others:

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帰属
所属していません StackOverflow
scroll top