# 从163邮箱发到qq邮箱为例子
注册一个163邮箱并开通smtp服务,注册一个qq邮箱
# coding:utf-8 # python2
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import time
my_sender = 'xxx@163.com'
my_sender_pw = '授权密码'
my_user = 'xxx@qq.com'
def mail():
ret = True
try:
msg = MIMEText('发送内容', 'plain', 'utf-8')
msg['From'] = formataddr(["发件人邮箱昵称", my_sender])
msg['To'] = formataddr(["收件人邮箱昵称", my_user])
msg['Subject'] = "发送主题"
server = smtplib.SMTP("smtp.163.com", 25) # 端口是25
server.login(my_sender, my_sender_pw)
server.sendmail(my_sender, [my_user, ], msg.as_string())
server.quit()
except Exception:
ret = False
return ret
ret = mail()
if ret:
print("ok")
else:
print("failed")
还有一个更简单的用yagmail库
import yagmail # 登录你的邮箱 yag = yagmail.SMTP(user = 'xxx@qq.com', password = '授权码', host = 'smtp.qq.com') # 发送邮件 yag.send(to = ['aa@qq.com',"bbb@qq.com"], subject = '邮件的主题', contents = ['我要发送的内容heiha',"有时间随便回复我一个邮件"])