python3学习笔记之十——利用smtp,通过163邮箱发送邮件

通过smtp发送邮件一直提示在登录的时候身份认证失败,百度了一下才知道163邮箱需要在设置里面开通smtp服务,并且设置授权码,通过第三方登录163邮箱的时候,登录的密码就是这个授权码,问题搞清楚了,接下来就是正常邮件的发送了。

163的smtp的服务器地址:smtp.163.com

import smtplib
from email.mime.text import MIMEText

msg_from = '*****@163.com'
passward = '*****' #授权码
msg_to = '******@qq.com'

subject = '这是测试邮件'
content = '这是用python和smtp模块发送的邮件'

msg = MIMEText(content)
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = msg_to

try:
s = smtplib.SMTP('smtp.163.com',25)
s.login(msg_from,passward)
s.sendmail(msg_from,msg_to,msg.as_string())
print('发送成功')
except smtplib.SMTPException as e:
print('发送失败' + format(e))
finally:
s.quit()

在内容里发送html文件,只需将:

content = '<html><body><h1>Hello</h1>' \
'<p>send by <a href="http://www.python.org">Python</a>...</p>' \
'</body></html>'

msg = MIMEText(content,'html','utf-8')

这样发送的文件就是html文件了,效果如下:

python3学习笔记之十——利用smtp,通过163邮箱发送邮件

发送带附件的邮件,相当于包含若*分的邮件,包含文本和附件。

定义邮件对象:

msg = MIMEMultipart()

通过msg.attach将其他部分添加上去发送即可。

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

msg_from = '******@163.com'
passward = '***'
msg_to = '*****@qq.com'

subject = '这是测试邮件'
content = '<html><body><h1>Hello</h1>' \
'<p>send by <a href="http://www.python.org">Python</a>...</p>' \
'</body></html>'

#msg = MIMEText(content,'html','utf-8')
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = msg_to

#添加html内容
msg.attach(MIMEText(content,'html','utf-8'))

#添加附件
with open(r'C:\1.jpg','rb') as f:
mime = MIMEBase('image','jpg',filename='1.jpg')
mime.add_header('Content-Disposition','attachment',filename='1.jpg')
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
try:
s = smtplib.SMTP('smtp.163.com',25)
s.login(msg_from,passward)
s.sendmail(msg_from,msg_to,msg.as_string())
print('发送成功')
except smtplib.SMTPException as e:
print('发送失败' + format(e))
finally:
s.quit()


如果要发送2个附件图片呢?

只需将下面这个序号更改一下,添加就可以了。

mime.add_header('Content-ID', '<1>')
mime.add_header('X-Attachment-Id', '1')


python3学习笔记之十——利用smtp,通过163邮箱发送邮件

假如需要增加一个附件是文本文件,只需将附件类型更改一下,再将序号更改一下就行了:

mime = MIMEBase('text','txt',filename='4.txt') #更改内容
mime.add_header('Content-Disposition','attachment',filename='4.txt')
mime.add_header('Content-ID', '<2>')
mime.add_header('X-Attachment-Id', '2')