Python通过email和smtplib模块发送简单邮件

  SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import即可使用。smtplib模块主要负责发送邮件,email模块主要负责构造邮件。

  smtplib模块主要负责发送邮件:是一个发送邮件的动作,连接邮箱服务器,登录邮箱,发送邮件(有发件人,收信人,邮件内容)。email模块主要负责构造邮件:指的是邮箱页面显示的一些构造,如发件人,收件人,主题,正文,附件等。

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 邮箱服务器,我使用的是163邮箱
smtpserver = ‘smtp.163.com‘
user = ‘[email protected]‘
# 授权码不是密码
password = ‘********‘
# 发件人
sender = ‘[email protected]‘
# 收件人
receiver = ‘[email protected]‘
# 邮件主题
subject = ‘python test‘
# 编写Html类型的邮件内容
msg = MIMEText("<html><h1>你好!</h1></html>",‘html‘,‘utf8‘)
msg[‘Subject‘] = Header(subject,‘utf8‘)

# 连接发送 smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(user,password) smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit()

  下面用yagmail发送:

import yagmail

# 连接邮箱服务器
yag = yagmail.SMTP(user=‘[email protected]3.com‘,password=‘********‘,host=‘smtp.163.com‘)
# 编辑邮箱内容,可写多段
content = [‘python test‘]

yag.send(‘[email protected]‘,‘主题‘,content)

相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...