python实现邮件发送
python使用邮箱服务器发送qq邮件
对发送邮件的代码进行封装成函数后调用
导入需要使用的库
import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.header import Headerfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImage
封装发送邮件函数
需要在qq邮箱的账户设置中开启POP3/SMTP服务
保存POP3/SMTP服务授权码
def send_mail_demo(sender,to,subject,context,imageName):# 连接邮件服务器conn = smtplib.SMTP_SSL('', 465)# 登录conn.login('123456@', 'POP3/SMTP服务授权码') # 用户名 和授权码# 生成邮件发送对象email_obj = MIMEMultipart()# 邮件主题email_obj['Subject'] = Header(subject, 'utf-8').encode()# 内容context = MIMEText(context, _charset='utf-8')context = MIMEText('需要发送的内容', _charset='utf-8')
附件的发送
with open(imageName,'rb') as fp:data = fp.read()context1 = MIMEImage(data)context1['Content-Disposition'] = 'attechment;filename="image.png"' # image.png设置对方看到的图片的名称email_obj.attach(context1)# 发送邮件conn.sendmail(sender,to,email_obj.as_string())
调用函数发送
from MailSend.new_mail_send import send_mail_demosend_mail_demo('123456@',['123456@'],'十点整么','何以解忧,唯有暴富,何以暴富,唯有爱我','表白.png')