I can send emails, but not replies with smtplib and GMail
<p>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 <code>smtplib</code>.</p>

<p>This is the code I use for sending plain mails (suppose that <code>foobar@gmail.com</code> is my personal email):</p>

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

<p>This is what I use to send replies:</p>

<pre><code>print smtpserver.sendmail(
    "Giul Mus &lt;giul.mus@gmail.com&gt;",
    str(params["From"]),
    msg,
    {
        "In-Reply-To": params["Message-ID"],
        "Message-ID": email.utils.make_msgid(),
        "References": params["Message-ID"],
        "Subject": "Re: " + params["Subject"]
    }
)
</code></pre>

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

<pre><code>Traceback (most recent call last):
  File "imap.py", line 65, in &lt;module&gt;
    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 &lt;foobar@gmail.com&gt;')
</code></pre>

<p>Why does this happen? I saw <a href="http://stackoverflow.com/questions/4321346/555-5-5-2-syntax-error-gmails-smtp">this</a>, question, but it wasn't of any help (I tried sending it from <code>"Foo Bar &lt;foobar@gmail.com&gt;"</code>, <code>"&lt;foobar@gmail.com&gt;"</code>, or to <code>"&lt;hardcoded-address@gmail.com&gt;"</code>, but none of these worked).</p>

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

<pre><code>msg = MIMEMultipart("mixed")
body = MIMEMultipart("alternative")
body.attach(MIMEText(text, "plain"))
body.attach(MIMEText("&lt;html&gt;" + text + "&lt;/html&gt;", "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(
    "&lt;foobar@gmail.com&gt;",
    destination,
    msg.as_string()
)
</code></pre>

python email smtp gmail