Python-发送邮件

通过 Python 自动发送邮件,用于监测服务。

这里的发送内容,定义为 html 格式,同时可以附加图片。

# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart


def sendEmail(subject, content, imagePath):

    sender = 'xxx@qq.com'
    reveicers = ['xxx@qq.com', 'xxx@qq.com']

    msg = MIMEMultipart()

    msg['From'] = sender
    msg['To'] = ','.join(reveicers)
    msg['Subject'] = subject
    msg.attach(MIMEText(content, 'html', 'utf-8'))
    fp = open(imagePath, 'rb')
    image = MIMEImage(fp.read())
    msg.attach(image)
    fp.close()

    try:
        smtp = smtplib.SMTP(host='smtp.qq.com', port=465)
        smtp.sendmail(sender, reveicers, msg.as_string())
        smtp.quit()
    except Exception, e:
        print e

对于,需要安全认证的服务,举例如下:

smtp = smtplib.SMTP(host='smtp.qq.com', port=465)
smtp.set_debuglevel(True)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(USER, PASS)