Giulio Muscarello
Giulio Muscarello

Reputation: 1341

I can send emails, but not replies with smtplib and GMail

I'm making a program that replies automatically to emails on my GMail account. I can send mails just fine, but I can't seem to reply to them. I'm using smtplib.

This is the code I use for sending plain mails (suppose that [email protected] is my personal email):

# params contains the header data of the original email.
print smtpserver.sendmail(
    "Name Surname <[email protected]>",
    str(params["From"]),
    msg
)

This is what I use to send replies:

print smtpserver.sendmail(
    "Giul Mus <[email protected]>",
    str(params["From"]),
    msg,
    {
        "In-Reply-To": params["Message-ID"],
        "Message-ID": email.utils.make_msgid(),
        "References": params["Message-ID"],
        "Subject": "Re: " + params["Subject"]
    }
)

The former works correctly, and I can see the mail it sent in my mailbox; however, the latter fails with this stack trace:

Traceback (most recent call last):
  File "imap.py", line 65, in <module>
    imapprocess(imapdata[0].split(" "))
  File "imap.py", line 55, in imapprocess
    raise e
smtplib.SMTPSenderRefused: (555, '5.5.2 Syntax error. o2sm22774327wjo.3 - gsmtp', 'Name Surname <[email protected]>')

Why does this happen? I saw this, question, but it wasn't of any help (I tried sending it from "Foo Bar <[email protected]>", "<[email protected]>", or to "<[email protected]>", but none of these worked).

Upvotes: 0

Views: 433

Answers (1)

Giulio Muscarello
Giulio Muscarello

Reputation: 1341

The options are not to be passed as an argument, but for whatever reason they actually belong in the message. Here is an example:

msg = MIMEMultipart("mixed")
body = MIMEMultipart("alternative")
body.attach(MIMEText(text, "plain"))
body.attach(MIMEText("<html>" + text + "</html>", "html"))
msg.attach(body)
msg["In-Reply-To"] = params["Message-ID"]
msg["Message-ID"] = email.utils.make_msgid()
msg["References"] = params["Message-ID"]
msg["Subject"] = "Re: " + params["Subject"]
destination = msg["To"] = params["Reply-To"] or params["From"]
smtpserver.sendmail(
    "<[email protected]>",
    destination,
    msg.as_string()
)

Upvotes: 1

Related Questions