简介
简单的邮件发送脚本,功能与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()
增强版(支持TLS, SSL):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#功能与msmtp类似,可作为mutt的邮件发送代理
import sys
import email
import smtplib
class Config:
MAIL_SERVER = ''
MAIL_PORT = 25
MAIL_USERNAME = ''
MAIL_PASSWORD = ''
TIMEOUT = 5.0
# gmail, hotmail的话下面这行注释去掉
# MAIL_USE_TLS = True
# qq企业邮箱的话下面这行注释去掉
# MAIL_USE_SSL = True
def main():
secure = None
if getattr(Config, 'MAIL_USE_TLS', None):
secure = ()
use_ssl = getattr(Config, 'MAIL_USE_SSL', False)
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]
_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.MAIL_USERNAME:
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__":
main()