Home » Python » sendmail.py / msmtp.py
  • 24
  • 10月

sendmail.py / msmtp.py

用Python编写的简单的邮件发送脚本,功能与mstmp等类似,可直接作为mutt的MTA。

目录:

[TOC]

增强版(支持TLS,SSL)

配置文件

存放位置:~/.msmtpyrc

# -*- coding: utf-8 -*-

MAIL_SERVER = ''
MAIL_PORT = 25
MAIL_USERNAME = ''
MAIL_PASSWORD = ''

TIMEOUT = 10.0

# gmail, hotmail的话下面这行注释去掉
#MAIL_USE_TLS = True

# qq企业邮箱的话下面这行注释去掉
#MAIL_USE_SSL = True

msmtp.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#功能与msmtp类似,可作为mutt的邮件发送代理

import os
import sys
import imp
import email
import smtplib


def _load_config():
    _config = {}
    _homedir = os.path.expanduser('~')
    _filename = os.path.join(_homedir, '.msmtpyrc')

    obj = imp.load_source('config', _filename)
    for key in dir(obj):
        if key.isupper():
            _config[key] = getattr(obj, key)
    return _config


def sendmail():

    Config = _load_config()

    secure = None
    if Config.get('MAIL_USE_TLS', None):
        secure = ()
    use_ssl = Config.get('MAIL_USE_SSL', False)

    data = sys.stdin.read()
    msg = email.message_from_string(data)
    FROM = email.utils.parseaddr(msg.get("from"))[1]
    TO = []
    for _to in msg.get('to').split(','):
        TO.append(email.utils.parseaddr(_to)[1])
    _subject = email.Header.Header(msg.get('subject'))
    SUBJECT = email.Header.decode_header(_subject)[0][0]
    print( 'connect smtp server %s ...' % Config['MAIL_SERVER'])

    if use_ssl:
        smtp = smtplib.SMTP_SSL(Config['MAIL_SERVER'], Config['MAIL_PORT'],
                                timeout=Config['TIMEOUT'])
    else:
        smtp = smtplib.SMTP(Config['MAIL_SERVER'], Config['MAIL_PORT'],
                            timeout=Config['TIMEOUT'])

    if Config.get('MAIL_USERNAME', None):
        if secure is not None:
            smtp.ehlo()
            smtp.starttls(*secure)
            smtp.ehlo()
        smtp.login(Config['MAIL_USERNAME'], Config['MAIL_PASSWORD'])
    print( 'send mail [%s] to %s ...' % (SUBJECT, TO))
    smtp.sendmail(FROM, TO, msg.as_string())
    smtp.quit()
    print( 'mail sended. ^_^')


if __name__ == '__main__':
    sendmail()

旧版

简介

简单的邮件发送脚本,功能与mstmp等类似,可直接作为mutt的MTA。

配置文件

配置文件为:~/.wsmtprc

格式:

[smtp]
host=smtp.qq.com
port=25
user=yourname
passwd=yourpasswd

源码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#功能与msmtp类似,可作为mutt的邮件发送代理
import sys,smtplib
import email
import ConfigParser
from os.path import exists, expanduser
def main():
    home = expanduser('~')
    rcfile = "%s/.wsmtprc" % home
    if not exists(rcfile):
        print ('none config file!/n')
        return

    cf = ConfigParser.ConfigParser()
    cf.read(rcfile)
    host = cf.get("smtp", "host")
    port = cf.getint("smtp", "port")
    user = cf.get("smtp", "user")
    passwd = cf.get("smtp", "passwd")
    data = sys.stdin.read()
    msg = email.message_from_string(data)
    FROM = email.utils.parseaddr(msg.get("from"))[1]
    TO = email.utils.parseaddr(msg.get("to"))[1]
    h = email.Header.Header(msg.get('subject'))
    SUBJECT = email.Header.decode_header(h)[0][0]
    print( 'connect smtp server %s ...' % host)

    smtp = smtplib.SMTP()
    smtp.connect('%s:%d' %(host, port))
    smtp.login(user, passwd)
    print( 'send mail [%s] to <%s> ...' % (SUBJECT,TO))
    smtp.sendmail(FROM, TO, data)
    smtp.quit()
    print( 'mail sended. ^_^')
if __name__ == "__main__":
    main()