当前位置: 代码迷 >> 综合 >> python2-使用python发送邮件工具
  详细解决方案

python2-使用python发送邮件工具

热度:104   发布时间:2023-10-16 13:10:46.0

功能:发邮件、多人发送、发附件

#!/usr/bin/python
# -*- coding: utf-8 -*-
#python2import smtplib,os,sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email import encoders
from email.mime.base import MIMEBase
from email.utils import parseaddr, formataddr
# 格式化邮件地址
def formatAddr(s):name, addr = parseaddr(s)return formataddr((Header(name, 'utf-8').encode(), addr))
def sendMail(body, attachment):smtp_server = 'smtp.exmail.qq.com'from_mail = 'xxx@xxx'mail_pass = '********'to_mail = ['邮箱1','邮箱2','邮箱3']# 构造一个MIMEMultipart对象代表邮件本身msg = MIMEMultipart()# Header对中文进行转码msg['From'] = formatAddr('来自哪里 <%s>' % from_mail).encode()msg['To'] = ','.join(to_mail)msg['Subject'] = Header('抬头', 'utf-8').encode()# plain代表纯文本msg.attach(MIMEText(body, 'plain', 'utf-8'))# 二进制方式模式文件with open(attachment, 'rb') as f:# MIMEBase表示附件的对象mime = MIMEBase('text', 'txt', filename=attachment)# filename是显示附件名字mime.add_header('Content-Disposition', 'attachment', filename=attachment)# 获取附件内容mime.set_payload(f.read())encoders.encode_base64(mime)# 作为附件添加到邮件msg.attach(mime)server = smtplib.SMTP(smtp_server, 25)server.set_debuglevel(1)server.login(from_mail, mail_pass)print(2)print(type(msg))server.sendmail(from_mail, to_mail, msg.as_string())  # as_string()把MIMEText对象变成strserver.quit()if __name__ == "__main__":filer=sys.argv[1]sendMail('附件是测试数据, 请查收!', filer)