Python的邮件发送功能模块编写


=Start=

缘由:

之前用Python写过发送邮件的功能,但每次在使用的时候还不太方便,所以考虑着整理一下放在这里,方便以后使用、参考。

正文:

参考解答:
  • 抄送(CC)
  • 密送(BCC)
#!/usr/bin/env python
# coding=utf-8

import logging
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

class SendMail(object):
    def __init__(self, host='smtp.qq.com', port=587, user='', passwd=''):
        self.s = smtplib.SMTP('{0}:{1}'.format(host, port))

    def mail(self, subject, content, mail_from, mail_to_str, mail_cc_str='', mail_bcc_str=''):
        if isinstance(subject, unicode):
            subject = subject.encode('utf-8')
        if isinstance(content, unicode):
            content = content.encode('utf-8')

        msg = MIMEMultipart('alternative')
        msg['subject'] = str(subject).decode('utf-8')
        msg['From'] = mail_from
        msg['To'] = mail_to_str
        msg['Cc'] = mail_cc_str
        msg['Bcc'] = mail_bcc_str
        mail_to_all = mail_to_str.split(",") + mail_cc_str.split(",") + mail_bcc_str.split(",")

        msg.attach(MIMEText(content, 'plain', 'utf-8'))

        try:
            self.s.ehlo()
            self.s.starttls()
            self.s.login(user, passwd)
            self.s.sendmail(msg['From'], mail_to_all, msg.as_string())
            self.s.quit()
        except StandardError as e:
            logging.error('Sent email Error: {0}'.format(e))


def send_email(subject, content, mail_to, mail_cc='', mail_bcc=''):
    if isinstance(subject, unicode):
        subject = subject.encode('utf-8')
    if isinstance(content, unicode):
        content = content.encode('utf-8')

    msg = MIMEMultipart('alternative')
    msg['subject'] = str(subject).decode('utf-8')
    msg['From'] = '[email protected]'
    msg['To'] = mail_to
    msg['Cc'] = mail_cc
    msg['Bcc'] = mail_bcc
    mail_to_all = mail_to.split(",") + mail_cc.split(",") + mail_bcc.split(",")

    msg.attach(MIMEText(content, 'plain', 'utf-8'))

    try:
        s = smtplib.SMTP('smtp.qq.com:587')
        s.ehlo()
        s.starttls()
        s.login('user', 'passwd')
        s.sendmail(msg['From'], mail_to_all, msg.as_string())
        s.quit()
    except StandardError as e:
        logging.error('Sent email Error: {0}'.format(e))

 

参考链接:

=END=

,

《“Python的邮件发送功能模块编写”》 有 1 条评论

  1. 用Python发送 HTML格式 的邮件
    https://stackoverflow.com/questions/882712/sending-html-email-using-python
    http://www.runoob.com/python/python-email.html
    https://docs.python.org/2/library/email-examples.html
    `
    # 可以考虑将 ‘html’/’plain’ 作为参数传入,方便控制,但一般情况下都用 html 也没啥问题
    msg.attach(MIMEText(content, ‘html’, ‘utf-8’)) #以 HTML格式 发送
    msg.attach(MIMEText(content, ‘plain’, ‘utf-8’)) #以 文本格式 发送
    `

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注