import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header def send_email(sender, receiver, text, subject): """ 发送纯文本邮件 :param sender: :param receiver: :param text: :param subject: :return: """ mail_host = 'smtp.qq.com' # qq邮箱服务地址 smt = smtplib.SMTP() # #实例化SMTP类,这样就可以调用SMTP对象的方法和属性 smt.connect(mail_host, '25') # 连接服务器,第二个参数为端口号 password = "mmmmmm" # 邮箱登录密码(需要进入qq邮箱->设置->账号->获取密码) try: smt.login(sender, password) # 登录邮箱,第一参数是发件人邮箱账号、第二个为邮箱登录密码 message = MIMEText(text, 'plain', 'utf-8') # 实例化一个MIMEText邮件对象,该对象需要写进三个参数,分别是邮件正文,文本格式和编码 message['Subject'] = Header(subject, 'utf-8') # 邮件标题 try: smt.sendmail(sender, receiver, message.as_string()) # 发送邮件操作 print("邮件发送成功") except: print("邮件发送失败") except: print("登录失败,请检测邮箱、密码是否正确") smt.quit() # 退出邮箱
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header def send_file(sender, receiver, file, subject): """ 发送带附件的邮件 :param sender: :param receiver: :param data: :param subject: :return: """ addr = 'smtp.qq.com' smt = smtplib.SMTP() smt.connect(addr, '25') password = "mmmmmm" smt.login(sender, password) message = MIMEMultipart() message['Subject'] = Header(subject, 'utf-8') message['From'] = Header(sender, 'utf-8') message['To'] = Header(receiver, 'utf-8') message.attach(MIMEText("最近一周天气情况", 'plain', 'utf-8')) att1 = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8') att1['Content-Type'] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment, filename="weather.txt' message.attach(att1) smt.sendmail(sender, receiver, message.as_string())
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header import schedule import time def job(): """ 定时发送邮件 :return: """ file = writer_data(get_data()) send_file(sender, receiver, file, subject) schedule.every(2).minutes.do(job) while True: schedule.run_pending() time.sleep(2)