思路
首先开启所用邮箱的smtp服务
此处示例为QQ邮箱
登录邮箱首页->设置->账户->开启POP3/SMTP服务->发送信息->保存授权码
代码实例
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from code_base64 import Char_To_Base64
#使用第三方SMPT服务
mail_host="smtp.qq.com" #设置服务器
mail_user="你使用的邮箱" #用户名
mail_pass="你使用邮箱的口令" #填写授权码
sender='发送邮件的邮箱'
receivers=['收到邮件的邮箱'] #收件人数组
message=MIMEText('邮件正文','plain','utf-8')
#此处使用了自己写的汉字转base64编码的类Char_To_Base64中的方法encode(str)
s="测试一下"
base64str=Char_To_Base64.encode(s)
#此处注意from是有格式的,如果昵称使用中文必须使用base64编码
message['from']='"=?utf-8?B?'+base64str+'?=" <发送邮件的邮箱>'
message['To']=Header("测试",'utf-8')
#邮件主题
subject='没有主题就是玩'
message['Subject']=Header(subject,'utf-8')
try:
smptObj=smtplib.SMTP()
smptObj.connect(mail_host,25) #25为SMTP端口号
smptObj.login(mail_user,mail_pass)
smptObj.set_debuglevel(1) #显示与服务器交互的所有信息
smptObj.sendmail(sender,receivers,message.as_string())
smptObj.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("无法发送文件")
from格式说明
如果昵称使用汉字必须用base64进行编码,可以用python引入base64库,再使用函数实现,此处不做详细讲解,可以参考https://blog.csdn.net/weixin_44799217/article/details/125949538
此处使用的是自己手动实现的base64编码,传入想转换的字符串即可转换成base64编码
s=“测试一下”
base64str=Char_To_Base64.encode(s)
详情请参考我得另外一篇文章(附源码)https://blog.csdn.net/qq_44398094/article/details/129820164
即From格式为:
message[‘from’]= ‘"=?utf-8?B?’+base64编码后的内容+‘?=" <发送邮件的邮箱>’
参考文章
https://jiuaidu.com/it/2005548/
https://blog.csdn.net/weixin_53013159/article/details/122818091
https://www.runoob.com/python/python-email.html