import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import os
def send_email(username,password,subject,from_email,to_email,sender, receiver,dir_path):
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com',25)
smtp.login(username, password)
msg = MIMEMultipart('mixed')
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
text_plain = MIMEText(text, 'plain', 'utf-8')
msg.attach(text_plain)
fileName_list = os.listdir(dir_path)
filePath_list = [os.path.join(dir_path, imageName) for imageName in fileName_list]
print(filePath_list)
if len(filePath_list) != 0:
for i in range(len(filePath_list)):
if os.path.isfile(filePath_list[i]):
att = MIMEText(open(filePath_list[i], 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att.add_header("Content-Disposition", "attachment", filename=("gbk", "", "%s"%filePath_list[i]))
msg.attach(att)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
username = "******"
password = "******"
sender = "******"
receiver = "******"
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"
subject = 'Python email test'
from_email = '******'
to_email = '******'
dir_path = r'D:\report'
send_email(username,password,subject,from_email,to_email,sender, receiver,dir_path)