开发语言: python2.7
包:smtplib


导入包:

import smtplib


定义一个函数:

def send_mail(to_list, cc_list, html, sub):
    me = mail_user
    msg = MIMEText(html, _subtype='html', _charset='utf-8')  # 格式化邮件内容为html,编码为utf-8
    msg['Subject'] = sub    # 邮件主题
    msg['From'] = me    # 发件人
    msg['To'] = ";".join(to_list)  # 收件人,将列表转换为字符串
    msg['Cc'] = ";".join(cc_list)  # 抄送人,将列表转换为字符串
    try:
        send_smtp = smtplib.SMTP()    # 实例化
        send_smtp.connect(mail_host)    # 连接smtp服务器
        send_smtp.login(mail_user, mail_pass)    # 使用定义的账号密码进行登录
        send_smtp.sendmail(me, to_list+cc_list, msg.as_string())    # 发送邮件
        send_smtp.close()    # 关闭连接
        return True
    except Exception, e:
        # logging.debug(e)
        print e
        return False

  其中:“to_list”为收件人列表(可以为一个或者多个),“cc_list”为抄送列表(同样为一个或多个),“html”为邮件内容,可以发送html格式的邮件,“sub”为邮件主题。


调用发送邮件函数:

if __name__ == '__main__':
    mail_host = 'xxx@163.com'
    mail_user = 'user@163.com'
    mail_pass = 'password'
    mailto_list = ['user1@qq.com', 'user2@qq.com', 'user3@qq.com']
    mailcc_list = ['5086×××9@163.com']
    html = "<h1> test page</h1>"
    sub = "send mail test"
    if send_mail(mailto_list, mailcc_list, strhtml, sub):
        logging.debug("Send mail succed!")
    else:
        logging.debug("Send mail failed")

  在搜索资料过程中,发现很多人说抄送功能无法实现,可能是因为列表和字符串之间的转换问题,或者是由于send_smtp.sendmail()函数的格式问题,虽然没有报错,但是没有发送成功。

建议大家在使用时,如果没有发送成功或者是抄送成功,可以在

to_list,cc_list,msg['To'],msg['Cc']

这里加上print,看一下类型和是否正确;


附smtplib源码地址:

https://hg.python.org/cpython/file/2.7/Lib/smtplib.py