Tôi đang viết một người gửi smtp đơn giản với xác thực. Đây là mã của tôiCách đặt bộ ký tự trong email bằng cách sử dụng smtplib trong Python 2.7?
SMTPserver, sender, destination = 'smtp.googlemail.com', '[email protected]', ['[email protected]']
USERNAME, PASSWORD = "user", "password"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""
Hello, world!
"""
subject="Message Subject"
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
from email.MIMEText import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.close()
except Exception, exc:
sys.exit("mail failed; %s" % str(exc)) # give a error message
Nó hoạt động hoàn hảo, cho đến khi tôi cố gắng gửi các ký hiệu không phải ascii (cyrillic Nga). Làm thế nào tôi nên xác định một bảng mã trong một tin nhắn để làm cho nó hiển thị một cách thích hợp? Cảm ơn trước!
UPD. Tôi đã thay đổi mã của tôi:
text_subtype = 'text'
content="<p>Текст письма</p>"
msg = MIMEText(content, text_subtype)
msg['From']=sender # some SMTP servers will do this automatically, not all
msg['MIME-Version']="1.0"
msg['Subject']="=?UTF-8?Q?Тема письма?="
msg['Content-Type'] = "text/html; charset=utf-8"
msg['Content-Transfer-Encoding'] = "quoted-printable"
…
conn.sendmail(sender, destination, str(msg))
Vì vậy, lần đầu tiên tôi spectify 'text' text_subtype =, và sau đó trong tiêu đề tôi đặt một msg [ 'Content-Type'] = "text/html; charset = utf -8 "chuỗi. Nó có đúng không?
CẬP NHẬT Cuối cùng, tôi đã giải quyết vấn đề thông điệp của tôi Bạn nên viết smth như msg = MIMEText (content.encode ('utf-8'), 'đơn giản', 'UTF-8')
Xin chào Lorcan! Làm thế nào về 'To' và 'From' nếu tôi sẽ chỉ định chúng trong msg của tôi (như msg ['From'] = '[email protected]')? Tôi nên mã hóa nó quá hay không? –