发邮件需要用到python两个模块,smtplib和email,这俩模块是python自带的,只需import即可使用。smtplib模块主要负责发送邮件,email模块主要负责构造邮件。其中MIMEText()定义邮件正文,Header()定义邮件标题。MIMEMulipart模块构造带附件
发送HTML格式的邮件:
send_email_html.py
发送带附件的邮件
send_email_file.py
- import smtplib
- from email.mime.text import MIMEText
- from email.mime.multipart import MIMEMultipart
-
-
- smtpserver = 'smtp.sina.com'
-
-
- user ="xxx@sina.com"
- password = "xxx"
-
-
- sender = "xxx@sina.com"
-
-
- receiver = "1xxx@qq.com"
-
-
- subject = "附件的邮件"
-
-
- sendfile = open("C:\\Users\\Administrator\\Desktop\\html5.txt","r").read()
-
- att = MIMEText(sendfile,"base64","utf-8")
- att["Content-Type"] = "application/octet-stream"
- att["Content-Disposition"] = "attachment;filename = 'html5.txt'"
-
- msgRoot = MIMEMultipart('related')
- msgRoot['Subject'] = subject
- msgRoot.attach(att)
-
- smtp = smtplib.SMTP()
- smtp.connect(smtpserver)
- smtp.login(user,password)
- smtp.sendmail(sender,receiver,msgRoot.as_string())
- smtp.quit()
Top