首页 > Python > python3_03发送邮件

python3_03发送邮件

  今天看了一下怎么用python3发邮件?遇见的主要问题还是字符的编码问题
  问题1:遇见UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range(128)。还是utf-8的问题,解决办法:用Header()显示的转换成UTF-8编码,这下问题就解决了。

代码如下:

# ------- sendmail.py -------  
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "xxxx@qq.com"
you = "xxxx@qq.com"
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('问候','utf-8')
msg['From'] = Header('猜猜我是谁','utf-8')
msg['To'] = you

text = "Hi!\n中文How are you?\nHere is the link you wanted:\n"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!呵呵<br>
       How are you?<br>
       解决个编码问题,可以发中文邮件了!
    </p>
  </body>
</html>
"""
part1 = MIMEText(text, 'plain','utf-8')
part2 = MIMEText(html, 'html','utf-8')

msg.attach(part1)
msg.attach(part2)
#print(msg.as_string())
s = smtplib.SMTP('smtp.xx.com','port')
s.login('name','password')
s.sendmail(me, you, msg.as_string())
s.quit()
print("OK")

参考:
#####class email.mime.application.MIMEApplication(_data, _subtype=’octet-stream’, _encoder=email.encoders.encode_base64, **_params)
Module: email.mime.application
A subclass of MIMENonMultipart, the MIMEApplication class is used to represent MIME message objects of major type application. _data is a string containing the raw byte data. Optional _subtype specifies the MIME subtype and defaults to octet-stream.
Optional _encoder is a callable (i.e. function) which will perform the actual encoding of the data for transport. This callable takes one argument, which is the MIMEApplication instance. It should use get_payload() and set_payload() to change the payload to encoded form. It should also add any Content-Transfer-Encoding or other headers to the message object as necessary. The default encoding is base64. See the email.encoders module for a list of the built-in encoders.
_params are passed straight through to the base class constructor.
#####class smtplib.SMTP
login(self, user, password)
Log in on an SMTP server that requires authentication.
The arguments are:
– user: The user name to authenticate with.
– password: The password for the authentication.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
This method will return normally if the authentication was successful.

  1. 还没有评论
评论提交中, 请稍候...

留言


可以使用的标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Trackbacks & Pingbacks ( 0 )
  1. 还没有 trackbacks