1. 实现功能
支持群发给多个人 支持带附件发送
2. 核心代码
def send_email(smtp_server, sender_name, from_mail, mail_pass, to_mails, subj, body, attachment=None):
msg = MIMEMultipart()
msg['From'] = Header(sender_name, 'utf-8')
msg['To'] = to_mails
msg['Subject'] = Header(subj, 'utf-8')
msg.attach(MIMEText(body, 'plain', 'utf-8'))
if attachment and os.path.exists(attachment):
with open(attachment, 'rb') as f:
mime = MIMEApplication(f.read())
mime.add_header('Content-Disposition', 'attachment', filename=attachment)
msg.attach(mime)
try:
s = smtplib.SMTP()
s.connect(smtp_server, 25)
s.login(from_mail, mail_pass)
s.sendmail(from_mail, to_mails.split(','), msg.as_string())
s.quit()
print('发送成功')
except Exception as e:
print(f'Error: {e}')
3. 完整代码
https://gitee.com/ferrisyu/CodingSea/tree/master/Python/email
4. 使用方法
# 使用说明:
python3 email_send.py smtp服务 发件人名字 发件人邮箱 发件箱密码 收件箱 邮件标题 邮件内容 附件文件路径
# 例如:
python3 email_send.py smtp.163.com 编程之海 codingsea@163.com QOFXWSDVHLMDRGFT 2481498999@qq.com,342345@qq.com 标题测试 body测试 attachFile.txt
编程之海 版权所有丨如未注明,均为原创丨转载请注明转自:https://codingsea.com/python_send_email/