0

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 foobar@gmail.com is my personal email):

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

This is what I use to send replies:

print smtpserver.sendmail(
    "Giul Mus <giul.mus@gmail.com>",
    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 <foobar@gmail.com>')

Why does this happen? I saw this, question, but it wasn't of any help (I tried sending it from "Foo Bar <foobar@gmail.com>", "<foobar@gmail.com>", or to "<hardcoded-address@gmail.com>", but none of these worked).

Community
  • 1
  • 1
Giulio Muscarello
  • 1,312
  • 2
  • 12
  • 33
  • According to [the doc](https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.sendmail), the fourth argument is "mail_options", or "a list of ESMTP options (such as 8bitmime) to be used in MAIL FROM commands." This is not what you are passing in. – Robᵩ Sep 26 '16 at 15:08
  • @Robᵩ What should I pass for `mail_options` instead, and where should I pass my options? Apologies, I don't have experience with SMTP and mail protocols. – Giulio Muscarello Sep 26 '16 at 15:11
  • You probably shouldn't pass anything in mail_options. A list of possible values is here: https://en.wikipedia.org/wiki/Extended_SMTP#Extensions, but you probably don't need any of them. – Robᵩ Sep 26 '16 at 15:47

1 Answers1

1

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(
    "<foobar@gmail.com>",
    destination,
    msg.as_string()
)
Giulio Muscarello
  • 1,312
  • 2
  • 12
  • 33