有勇气的牛排博客

python 发送邮件

有勇气的牛排 289 Python 2023-05-18 20:52:58

1. 可带图片附件

from email import encoders from email.header import Header from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from smtplib import SMTP def send_email(receivers, topic, imageName,content, sender, password): # 自己填好相关信息 for receiver in receivers: try: msg = MIMEMultipart() msg['From'] = Header(sender, 'utf-8') # 编辑邮件头 msg['To'] = Header(receiver, 'utf-8') msg['Subject'] = Header(topic, 'utf-8') msg.attach(MIMEText(content, 'plain', 'utf-8')) # 把正文附在邮件上 with open(imageName+'.png', 'rb') as f: mime = MIMEBase('image', 'png', filename='Hello.png') # 创建表示附件的MIMEBase对象,重新命名为test.png mime.add_header('Content-Disposition', 'attachment', filename=imageName+'.png') mime.set_payload(f.read()) # 读取附件内容 encoders.encode_base64(mime) # 对附件Base64编码 msg.attach(mime) # 把附件附在邮件上 server = SMTP('smtp.qq.com', 25) server.login(sender, password) server.sendmail(sender, receiver, msg.as_string()) print('发送成功!') except Exception as error: print(error) print('发送失败') continue if __name__ == '__main__': sender = '666@qq.com' password = 'xp6' receiver = ['6@qq.com'] topic = '邮件测试' content = '邮件测试,请勿回复' imageName = '1' # 附件 图片名字 send_email(receiver, topic, imageName,content, sender, password)

2. 仅发送文本

import random, time # 发送邮件 1 def send_email(SMTPServer, sender, passwd, message1, title, receiver): #发邮件的库 import smtplib #邮件文本 from email.mime.text import MIMEText #SMTP服务器 # SMTPServer = "smtp.qq.com" #发邮件的地址 # sender = "853386196@qq.com" #发送者邮箱的密码 # passwd = "bqnnmmtaillgbfcb" #设置发送的内容 message = message1 #转换成邮件文本 msg = MIMEText(message) #标题 主题 msg["Subject"] = title #发送者 msg["From"] = sender #创建SMTP服务器 mailServer = smtplib.SMTP(SMTPServer, 25) #登陆邮箱 mailServer.login(sender, passwd) #发送邮件 mailServer.sendmail(sender, receiver, msg.as_string()) #退出邮箱 mailServer.quit() return 0 # 发送邮件 1 def email(): #SMTP服务器 SMTPServer = "smtp.qq.com" sender = "853386196@qq.com" passwd = "wesfwzyfrwfabeae" message = "【九天创想 - 920社区】您的验证码:109443,该验证码5分钟内有效。" title = '920登录验证' receiver = ['1809296387@qq.com','603188080@qq.com'] send_email(SMTPServer, sender, passwd, message, title, receiver) email()

第三方库

pip install yagmail
import yagmail #链接邮箱服务器 yag = yagmail.SMTP( user="85336@qq.com", password="ygow", host='smtp.qq.com') # 邮箱正文 contents = ['This is the body, and here is just text http://somedomain/image.png', 'You can find an audio file attached.', '/local/path/song.mp3'] # 发送邮件 #yag.send('taaa@126.com', 'subject', contents) # 发给多个用户 #yag.send(['aa@126.com','bb@qq.com','cc@gmail.com'], 'subject', contents) # 发附件 yag.send('180929@qq.com', '发送附件', contents, ["1.png"]) print('发送成功')

留言

专栏
文章
加入群聊