Python3发送邮件和带附件发送邮件二合一(记录一下)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#sys.argv[1] 收件人 test1@qq.com,test2@qq.com
#sys.argv[2] 标题
#sys.argv[3] 内容
#sys.argv[4] 附件文件 1.csv,2.xlm
#给多个联系人发送邮件
#./python3_sendmail.py test1@qq.com,test2@qq.com title detail
#给多个联系人发送多个附件
#./python3_sendmail.py test1@qq.com,test2@qq.com title detail 1.csv,2.xlm
#给单个联系人发送附件
#./python3_sendmail.py test1@qq.com title detail 1.csv,
import sys
def send_email(email_receiver, email_subject, email_content, email_attanchment_address = None):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
sender = 'test@qq.com'
passwd = '1234567890'
receivers = email_receiver # 邮件接收人
msgRoot = MIMEMultipart()
msgRoot['Subject'] = email_subject
msgRoot['From'] = sender
if len(receivers) > 1:
msgRoot['To'] = ','.join(receivers) # 群发邮件
else:
msgRoot['To'] = receivers[0]
part = MIMEText(email_content)
msgRoot.attach(part)
if email_attanchment_address == None:
try:
s = smtplib.SMTP_SSL()
s.connect('smtp.exmail.qq.com')
s.login(sender, passwd)
s.sendmail(sender, receivers, msgRoot.as_string())
print('邮件发送成功')
except smtplib.SMTPException as e:
print('邮件发送失败')
finally:
s.quit()
else:
# 添加附件
for path in email_attanchment_address:
for one_file in path:
print('one_file: '+one_file)
txt_name = one_file.split('/')[-1]
part = MIMEApplication(open(one_file, 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=txt_name)
msgRoot.attach(part)
try:
s = smtplib.SMTP_SSL()
s.connect('hwsmtp.exmail.qq.com')
s.login(sender, passwd)
s.sendmail(sender, receivers, msgRoot.as_string())
print('邮件发送成功')
except smtplib.SMTPException as e:
print('邮件发送失败')
finally:
s.quit()
email_receiver = sys.argv[1]
email_receiver = email_receiver.split(',')
email_subject = sys.argv[2]
email_content = sys.argv[3]
if len(sys.argv) < 5:
send_email(email_receiver, email_subject, email_content)
else:
txt_path = sys.argv[4]
txt_path = txt_path.split(',')
email_attanchment_address = [txt_path]
send_email(email_receiver, email_subject, email_content, email_attanchment_address)
参考文章:
https://www.jianshu.com/p/d4aed6f32c69