1.发送邮件给多个收件人,具体代码如下
def sendmail(subject, content):
#发送者邮箱服务器
email_host = 'smtp.163.com'
#发送者账号
email_user = '发件人邮箱'
email_pwd = '发件人邮箱密码'
tolist =["收件人1","收件人2"]
cclist = ["抄送人1","抄送人2"]
me = email_user
# 三个参数:第一个为邮件正文,第二个 html 设置文本格式,第三个 utf-8 设置编码
#邮件正文
msg = MIMEText(content, 'html', 'utf-8') # 邮件内容
#邮件主题
msg['Subject'] = subject
#发件人邮箱
msg['From'] = me
#收件人邮箱
msg['To'] = ",". join(tolist)
#抄送人邮箱
msg['Cc'] = ",". join(cclist)
#实例化SMTP对象
smtp = smtplib.SMTP(email_host)
#登录邮件服务器
smtp.login(email_user, email_pwd)
#发送邮件,传入发件人,收件人+抄送人,msg转换为字符串
"""
msg为SMTP协议定义的格式,包含以下部分:
From: 发件人
To: 收件人
Cc:抄送人
Subject: 主题
正文
"""
smtp.sendmail(me, tolist+cclist, msg.as_string())
smtp.quit() # 发送完毕后退出smtp
print ('email send success.')
#调用发送邮件的方法
sendmail('主题', '我是一只猫')
2.发送带附件的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def sendmail(subject, content):
#发送者邮箱服务器
email_host = 'smtp.163.com'
#发送者账号
email_user = '发件人邮箱'
email_pwd = '发件人邮箱密码'
tolist =["收件人1","收件人2"]
cclist = ["抄送人1","抄送人2"]
me = email_user
# 三个参数:第一个为邮件正文,第二个 html 设置文本格式,第三个 utf-8 设置编码
#邮件正文
msg = MIMEText(content, 'html', 'utf-8') # 邮件内容
#邮件主题
msg['Subject'] = subject
#发件人邮箱
msg['From'] = me
#收件人邮箱
msg['To'] = ",". join(tolist)
#抄送人邮箱
msg['Cc'] = ",". join(cclist)
txt = MIMEText(content, 'plain', 'utf-8')
msg.attach(txt)
# 添加附件,从本地路径读取。如果添加多个附件,可以定义part_2,part_3等,
# 然后使用part_2.add_header()和msg.attach(part_2)即可。
part = MIMEApplication(open('附件路径及名称', 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename="附件在邮件中的名称")
msg.attach(part)
#实例化SMTP对象
smtp = smtplib.SMTP(email_host)
#登录邮件服务器
smtp.login(email_user, email_pwd)
#发送邮件,传入发件人,收件人+抄送人,msg转换为字符串
"""
msg为SMTP协议定义的格式,包含以下部分:
From: 发件人
To: 收件人
Cc:抄送人
Subject: 主题
正文
"""
smtp.sendmail(me, tolist+cclist, msg.as_string())
smtp.quit() # 发送完毕后退出smtp
print ('email send success.')
#调用发送邮件的方法
sendmail('主题', '我是一只猫')