如果你用的是outlook邮件发送,那么请看另外一篇文章
亲测,使用163邮箱发信,很多测试内容和标题会被退信,所以我用的qq的,不过自己公司邮箱发送更好
import smtplib
import os
#发送文字
from email.mime.text import MIMEText
#发送文件
# from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
sender = 'aaa@qq.com'
passwd = '****'
receiver = ["aaaaa@outlook.com","bbbbb@outlook.com"] # 多个收件人放在一个list里面
content = 'hello world'
subject = 'this is a test'
server = smtplib.SMTP_SSL("smtp.qq.com", 465)
server.login(sender,passwd) #如果程序需要先花很多时间去获取各种信息然后把信息发出来,那么千万别在程序开启的时候就login,要不然断开连接了,要发信的时候再login比较好
# 发送文字
msg = MIMEText(content, 'plain', 'utf-8') # 中文需参数‘utf-8’,单字节字符不需要
msg["Accept-Charset"] = "ISO-8859-1,utf-8"
msg["Accept-Language"] = "zh-CN"
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ','.join(receiver) # 这里必须要把多个邮箱按照逗号拼接为字符串
# 发送文件
file = 'E:\\files\hello_world.txt'
part = MIMEApplication(open(file, 'rb').read())
fname= os.path.split(file)[1]
part.add_header('Content-Disposition', 'attachment', filename=fname)
msg.attach(part)
try:
server.sendmail(sender, receiver, msg.as_string())
print('email sent')
except smtplib.SMTPException as e:
print(e)
其实用自家公司的邮箱最好了,不会被qq拦截,只需要知道以下几点就行
1: server(smtp.qq.com)这样的
2: 端口
3: 自己的邮箱
4: 邮箱密码