How to send an e-mail to the international address via smtplib
in Python?
If I use the following code
try:
server = None
msg = MIMEMultipart('alternative')
msg['From'] = formataddr((from_email_name, from_email))
msg['To'] = Header(to_email, 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
plain_text_part = MIMEText(plain_text_body, 'plain', _charset='utf-8')
msg.attach(plain_text_part)
html_part = MIMEText(html_body, 'html', _charset='utf-8')
msg.attach(html_part)
server = smtplib.SMTP(smtp_server)
server.starttls()
server.login(from_email, from_email_password)
server.sendmail(from_email, to_email, msg.as_string())
finally:
if server is not None:
server.quit()
then the script fails on the following line when I call this code with ñoñó1234@server.com
e-mail as a destination address (to_email):
server.sendmail(from_email, to_email, msg.as_string())
Output
'ascii' codec can't encode character u'\xf1' in position 9: ordinal not in range(128)
However if I change the sendmail
function call to the following
server.sendmail(from_email, to_email.encode('utf-8'), msg.as_string())
it fails with the following error:
{'\xc3\xb1o\xc3\xb1\xc3\xb31234@server.com': (555, '5.5.2 Syntax error. i7sm368361lbo.39 - gsmtp')}
I'm using GMail's SMTP server to send these e-mails.
How can I fix it?
Thanks in advance.