Python - comment envoyer un e-mail utf-8?
comment envoyer un e-mail utf8 s'il vous plaît?
import sys
import smtplib
import email
import re
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sendmail(firm, fromEmail, to, template, subject, date):
with open(template, encoding="utf-8") as template_file:
message = template_file.read()
message = re.sub(r"{{s*firms*}}", firm, message)
message = re.sub(r"{{s*dates*}}", date, message)
message = re.sub(r"{{s*froms*}}", fromEmail, message)
message = re.sub(r"{{s*tos*}}", to, message)
message = re.sub(r"{{s*subjects*}}", subject, message)
msg = MIMEMultipart("alternative")
msg.set_charset("utf-8")
msg["Subject"] = subject
msg["From"] = fromEmail
msg["To"] = to
#Read from template
html = message[message.find("html:") + len("html:"):message.find("text:")].strip()
text = message[message.find("text:") + len("text:"):].strip()
part1 = MIMEText(html, "html")
part2 = MIMEText(text, "plain")
msg.attach(part1)
msg.attach(part2)
try:
server = smtplib.SMTP("10.0.0.5")
server.sendmail(fromEmail, [to], msg.as_string())
return 0
except Exception as ex:
#log error
#return -1
#debug
raise ex
finally:
server.quit()
if __name__ == "__main__":
#debug
sys.argv.append("Moje")
sys.argv.append("newsletter@example.cz")
sys.argv.append("subscriber@example.com")
sys.argv.append("may2011.template")
sys.argv.append("This is subject")
sys.argv.append("This is date")
if len(sys.argv) != 7:
exit(-2)
firm = sys.argv[1]
fromEmail = sys.argv[2]
to = sys.argv[3]
template = sys.argv[4]
subject = sys.argv[5]
date = sys.argv[6]
exit(sendmail(firm, fromEmail, to, template, subject, date))
Sortie
> Traceback (most recent call last):
> File "C:Documents and SettingsAdministratorPlochaNewsletter-build-desktopsendmail.py",
> line 69, in <module>
> exit(sendmail(firm, fromEmail, to, template, subject, date))
>
> File "C:Documents and SettingsAdministratorPlochaNewsletter-build-desktopsendmail.py",
> line 45, in sendmail
> raise ex
>
> File "C:Documents and SettingsAdministratorPlochaNewsletter-build-desktopsendmail.py",
> line 39, in sendmail
> server.sendmail(fromEmail, [to], msg.as_string())
>
> File "C:Python32libsmtplib.py",
> line 716, in sendmail
> msg = _fix_eols(msg).encode('ascii') UnicodeEncodeError: 'ascii' codec
>
> can't encode character 'u011b' in
> position 385: ordinal not in
> range(128)
33
demandé sur
Martin Drlík
2011-05-06 14:31:47
1 réponses
Vous devez juste ajouter 'utf-8'
argument MIMEText
appels (il suppose que 'us-ascii'
par défaut).
Par exemple:
# -*- encoding: utf-8 -*-
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart("alternative")
msg["Subject"] = u'テストメール'
part1 = MIMEText(u'\u3053\u3093\u306b\u3061\u306f\u3001\u4e16\u754c\uff01\n',
"plain", "utf-8")
msg.attach(part1)
print msg.as_string().encode('ascii')
68
répondu
abbot
2011-05-06 11:09:50