1.先开通邮件的POP3/SMTP/IMAP,拿到授权密码,注意,不是邮箱密码
2.相关代码,里面涉及到的数据库和邮件,都是相对路径下的,可根据代码自行创建和维护
#!pip install PyEmail
import smtplib # smtp 简单邮件传输协议
from email.mime.text import MIMEText
from email.header import Header
import pandas as pd
from email.mime.multipart import MIMEMultipart
mail_host = 'smtp.163.com' # SMTP服务器IP,如果是163,可能是smtp.163.com
mail_user = 'xxxxx@163.com' # 用户名
mail_pass = '******' # 密码 授权密码,非邮箱密码
sender = 'xxxx@163.com' # 发件人邮箱与mail_user要一致
# 定义发送邮件函数,参数为邮箱联系人分组
def SendMail(group):
data = group.reset_index(drop=True)
receiver = data.loc[0,'邮箱'] #收件人从dataframe取
Excels = data['公司'].to_list()
#创建一个带附件的邮件实例
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = Header('成本会计一课', 'utf-8')
#邮件正文内容
msg.attach(MIMEText('hello everybody……', 'plain', 'utf-8'))
# 构造附件
for file in Excels:
msg_xlsx = MIMEText(open(r'邮件集合/'+file+'.xlsx', 'rb').read(), 'base64', 'utf-8')
msg_xlsx.add_header('Content-Disposition', 'attachment', filename=file+'.xlsx')
msg.attach(msg_xlsx)
#发送邮件
try:
smtpObj = smtplib.SMTP_SSL(mail_host, 465) #465 是SMTP 端口号
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receiver, msg.as_string())
print('邮件发送成功:'+receiver)
except smtplib.SMTPException:
print('Error: 无法发送邮件receiver:'+receiver)
# 使用函数
df1 = pd.read_excel('公司与邮箱数据.xlsx', sheet_name=0,converters = {'公司': str})
df1.groupby(['邮箱'], as_index=False).apply(SendMail)