Python自动发送邮件

一直想实现一种机制,定时做某些事,然后如果检验没通过,自动发送邮件,定时和检验都好做,自动发邮件一直没有一种简单的方法,不过自从接触了无所不能的python,一切都变得简单,这周可以弄到自动化检测当中去

下面这段code可以实现自动发送邮件,根据send和recv的地址,smtp要设置有效,我设置163邮箱是可以成功发送的

#/usr/bin/env python

import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

send_email = ‘flyaway.lihui@gmail.com’
recv_email = ‘flyaway.lihui@gmail.com’
message = MIMEMultipart(‘alternatvie’)
message[‘Subject’] = Header(‘Something wrong’, ‘utf-8’)
message[‘To’] = recv_email
message[‘From’] = r’%s <flyaway.lihui@gmail.com>’ % Header(‘HuiLi’,’utf-8′)

send_file = ‘ctest.txt’
html = open(send_file).read()
html_part = MIMEText(html, ‘html’)
html_part.set_charset(‘utf-8’)
message.attach(html_part)

try:
    s = smtplib.SMTP(‘smtp.gmail.com’)
    s.login(‘flyaway.lihui’, ‘your passwd’)
    s.sendmail(send_email, recv_email, message.as_string())
except Exception,e:
    print e

前面半段是组装邮件标题等信息,后半段就是读取send_file文件内容,然后作为邮件正文,最终发送给收件人

发表回复