Python发送邮件处理

今天要说的是Python发送邮件,其实发送邮件的代码都差不多,但是使用其他的邮件服务器,还是有很多的限制,这里就简要说明一下使用其他的邮件服务器发送邮件和自己建立邮件服务器发送邮件,主要是贴代码。

系统 Ubuntu 14.04.3

用163服务器发送邮件

优点:少量邮件需要发送的时候还是可以的,不用自建服务器,减少了服务器的开销

缺点:频繁发送会有问题,网络延迟严重,异步IO回调慢等

不要吐槽我用start_new_thread

# -*- coding: UTF-8 -*-
'''
jack.zh sen mail test.
'''
import thread        
import smtplib
from email.mime.text import MIMEText

from log import logger

From_email = {
    "mail_host" :"smtp.163.com",  #设置服务器
    "mail_user" :"user_name",    #用户名
    "mail_pass" :"xxxxxxxx",   #口令 
    "mail_postfix" :"163.com"  #发件箱的后缀 
}

def send_mail(to_list, sub, content):
    me="my_name"+"<"+From_email["mail_user"]+"@"+From_email["mail_postfix"]+">"
    msg = MIMEText(content,_subtype='html',_charset='utf-8')
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(to_list)
    try:
        server = smtplib.SMTP()
        server.connect(From_email["mail_host"])
        server.login(From_email["mail_user"],From_email["mail_pass"])
        server.sendmail(me, to_list, msg.as_string())
        server.close()
        return True
    except Exception, e:
        logger.error(str(e))
        logger.error(str(to_list))
        logger.error(str(sub))
        logger.error(str(content))


def send_mail_thread(mailto_list, subject, msg):
    if send_mail(mailto_list, subject, msg):
        logger.info("send mail success.") 
    else:
        logger.error("send mail fail.")
        logger.error(subject)
        logger.error(msg)


def util_send_email(msg, subject, emails):
    thread.start_new_thread(send_mail_thread, (emails, subject, msg))


if __name__ == '__main__':
    msg = "msg"

    mailto_list=["zzh.coder@qq.com"]
    if send_mail(mailto_list,"hello", msg):
        logger.error("yes")
    else:
        logger.error("no")

使用自建邮箱服务器发送sendmail

安装邮件服务:

apt-get install sendmail sendmail-cf squirrelmail spamassassin mailman mailutils sharutils

贴发送邮件代码:

#!/usr/bin/env python
#@author : zzh.coder@qq.com
#@desc: for mail sending.

import smtplib
import getopt
import sys
import os

from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase

from email.MIMEText import MIMEText
import email.Encoders as encoders


def send_mail(mail_from, mail_to, subject, msg_txt, files=[]):
    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = mail_from
    msg['To'] = mail_to

    # Create the body of the message (a plain-text and an HTML version).
    #text = msg
    html = msg_txt

    # Record the MIME types of both parts - text/plain and text/html.
    #part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')

    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    #msg.attach(part1)
    msg.attach(part2)

    #attachment
    for f in files:
        #octet-stream:binary data
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(f, 'rb').read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)

    # Send the message via local SMTP server.
    s = smtplib.SMTP('localhost')
    # sendmail function takes 3 arguments: sender's address, recipient's address
    # and message to send - here it is sent as one string.

    mailto_list = mail_to.strip().split(",")
    if len(mailto_list) > 1:
        for mailtoi in mailto_list:
            s.sendmail(mail_from, mailtoi.strip(), msg.as_string())
    else:
        s.sendmail(mail_from, mail_to, msg.as_string())

    s.quit()
    return True


def main():
    files = []
    try:
        opts, args = getopt.getopt(sys.argv[1:], "f:t:s:m:a:")
        for op, value in opts:
            if op == "-f":
                mail_from = value
            elif op == "-t":
                mail_to = value
            elif op == "-s":
                subject = value
            elif op == "-m":
                msg_txt = value
            elif op == "-a":
                files = value.split(",")
    except getopt.GetoptError:
        print(sys.argv[0] + " : params are not defined well!")

    print mail_from, mail_to, subject, msg_txt
    if files:
        send_mail(mail_from, mail_to, subject, msg_txt, files)
    else:
        send_mail(mail_from, mail_to, subject, msg_txt)

if __name__ == "__main__":
    main()

Demo over。

后面的说明:

  • 服务器需要接收邮件并处理等操作此处不说,那是一个比较庞大的问题了
  • 自建服务器也有失败的可能,在配置senmail的时候有很多配置需要了解,这里不做详解,只提供思路
  • 方法2完全可以指定发件箱的地址,在此发件箱去接收那边的回复邮件,手动处理
  • 方法一和二都可以完整的使用邮件基本的所有功能,比如模版,附件等等

jack.zh 02.18 Python 阅读  1278  次

Fork me on GitHub