import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import sys
import os
mailto_list = ['[email protected]']
mail_host = "smtp.163.com"
mail_user = "*****@163.com"
mail_pass = "******"
def send_mail(sub, content, files, path):
me = sub + "<" + mail_user + ">"
msg = MIMEMultipart()
msg.attach(MIMEText(content, _subtype='html', _charset='utf-8'))
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ",".join(mailto_list)
for file in files:
if os.path.isfile(path + '/' + file):
att = MIMEText(open(path + '/' + file, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att.add_header("Content-Disposition", "attachment", filename=("gbk", "", file))
msg.attach(att)
try:
server = smtplib.SMTP()
if mail_host == 'smtp.gmail.com':
server.connect(mail_host, port=587)
server.starttls()
else:
server.connect(mail_host)
server.login(mail_user, mail_pass)
server.sendmail(me, mailto_list, msg.as_string())
server.close()
print('Mail sent successfully')
return True
except Exception as e:
print('Mail sent failed')
print(sys.exc_info()[0], sys.exc_info()[1])
return False
if __name__ == '__main__':
files = ['1.xlsx', '2.txt']
send_mail('国内top200应用', '国内top200应用', files, '/home/data')