In Python I'm attempting to send a message via SMTPlib. However, the message is always sending the entire message in the from header, and I have no idea how to fix it. It wasn't doing it before, but now it's always doing it. Here is my code:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
def verify(email, verify_url):
msg = MIMEMultipart()
msg['From'] = 'pyhubverify@gmail.com\n'
msg['To'] = email + '\n'
msg['Subject'] = 'PyHub verification' + '\n'
body = """ Someone sent a PyHub verification email to this address! Here is the link:
www.xxxx.co/verify/{1}
Not you? Ignore this email.
""".format(email, verify_url)
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('pyhubverify@gmail.com', 'xxxxxx')
print msg.as_string()
server.sendmail(msg['From'], [email], body)
server.close()
Is there anything wrong with it, and is there a way I can fix it?
This line is the issue:
server.sendmail(msg['From'], [email], body)
You could fix it with:
server.sendmail(msg['From'], [email], msg.as_string())
You were sending the body
instead of the whole message; the SMTP
protocol expects the message to start with the headers... hence you are seeing the body
where the headers is supposed to be.
You also need to remove the newline characters. Per rfc2822 the line-feed characters are undesirable alone:
A message consists of header fields (collectively called "the header of the message") followed, optionally, by a body. The header is a sequence of lines of characters with special syntax as defined in this standard. The body is simply a sequence of characters that follows the header and is separated from the header by an empty line (i.e., a line with nothing preceding the CRLF).
Please try the following:
msg = MIMEMultipart()
email = 'recipient@example.com'
verify_url = 'http://verify.example.com'
msg['From'] = 'pyhubverify@gmail.com'
msg['To'] = email
msg['Subject'] = 'PyHub verification'
body = """ Someone sent a PyHub verification email to this address! Here is the link:
www.xxxx.co/verify/{1}
Not you? Ignore this email.
""".format(email, verify_url)
msg.attach(MIMEText(body, 'plain'))
print msg.as_string()