Heim  >  Artikel  >  Backend-Entwicklung  >  Implementieren Sie die Methode zum Senden von E-Mails mit Python

Implementieren Sie die Methode zum Senden von E-Mails mit Python

高洛峰
高洛峰Original
2017-03-20 11:14:561457Durchsuche

In diesem Artikel wird erläutert, wie Sie mit Python E-Mails senden

# coding=utf-8
import smtplib
from time import sleep
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(**param):
    '''
    发送邮件
    author:cdq
    :param param:{"username":"","password":"","from_addr":"","to_addr":"","smtpserver":"","subject":"","file_path":""}
    :file_path=文件路径
    :return:
    '''
    error = ""
    flag = True
    try:
        # from conf_isms.adconf import local_host_ip
        if not param['is_send']:
            flag = False
        msg = MIMEMultipart()

        content = '<span>您好:</span><br><span style="text-indent: 2em;">' \
                  '    数据报表已发至邮箱,请您查看</span><br><span>' \
                  '              祝您生活愉快!<span>'
        body = MIMEText(content, _subtype="html", _charset="utf-8")
        msg.attach(body)
        if isinstance(param['file_path'], list):
            for m in param['file_path']:
                att = MIMEText(open(m, 'rb').read(), 'base64', 'utf-8')
                file_name = m.split('/')[-1]
                att["Content-Type"] = 'application/octet-stream'
                att["Content-Disposition"] = 'attachment; filename="%s"' % file_name.encode('gbk')  # 防止下载文件名乱码
                msg.attach(att)
        msg['to'] = ';'.join(param['to_addr'])
        msg['from'] = param['from_addr']
        msg['subject'] = param['subject']
        sm = smtplib.SMTP(param['smtpserver'], port=25)
        # sm.set_debuglevel(1)
        sm.ehlo()
        sm.starttls()
        sm.ehlo()
        sm.login(param['username'], param['password'])
        sm.sendmail(param['from_addr'], param['to_addr'], msg.as_string())
        sleep(5)
        sm.quit()
        print "%s  send successfully" % param['file_path']
        flag = True
    except Exception, ex:
        traceback.print_exc()
        print "send Failed "
        flag = False
        error = "error %s" % str(ex)
    finally:
        return flag, error

Das obige ist der detaillierte Inhalt vonImplementieren Sie die Methode zum Senden von E-Mails mit Python. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn