2021SC@SDUSC
源码分析之framework/ActionMail.py
前言
本文的前驱文章为OSSIM项目研究记录(四)
讲的是 framework / Action.py 中的内容
一、库
import smtplib
from email.mime.text import MIMEText
#
# LOCAL IMPORTS
#
from Logger import Logger
1.1、smtplib模块。
SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
常见用法如下:(地址等是随便编的)
sender_maile='213213321@qq.com' # 发送方的邮箱地址
sender_pass = '12424334' # 邮箱提供的授权码,可在第三方登录
sftp_obj =smtplib.SMTP('smtp.qq.com', 25)
sftp_obj.login(sender_mail, sender_pass)
#三个参数分别是:发件人邮箱账号,收件人邮箱账号,发送的邮件体
sftp_obj.sendmail(sender_mail, receiver_mail, msg_root.as_string())
sftp_obj.quit()
创建邮箱对象`msg = MIMEMultipart()
设置邮箱内容`
# 设置邮件主题
subject = Header('哈哈哈', 'utf-8').encode()
msg['Subject'] = subject
# 设置邮件发送者
msg['From'] = 'XXX@163.com <XXXX@163.com>'
# 设置邮件接受者
msg['To'] = '124322554@qq.com'
# 添加文字内容
text = MIMEText('哈哈哈', 'plain', 'utf-8')
msg.attach(text)
1.2、Logger
此模块是同文件下的一个文件Logger.py,其源自python的logging库里的一个静态类改写。
主要功能为管理和记录日志。
二、方法
上图是ActionMail
类,定义了四个方法。
2.1、init
初始化email属性:有server,密码,用户,端口号,还有一个use_postfix,查了说是邮件服务器,没太明白。
def __init__(self, server,server_port, user, passwd, use_postfix):
"""Constructor
@param server: The email server
@param user: the email server user
@param passwd: the email user passwd
@param use_postfix: Send the email using postfix
"""
self.__server = server
self.__passwd = passwd
self.__user = user
self.__port = server_port
self.__use_postfix = use_postfix
2.2、sendmail_postfix
尝试使用postfix本地服务器发送电子邮件。
logger.info(),传递信息
stmp.connect(),连接服务器,timeout是有效时间10s
def __sendmail_postfix(self, sender, recipients,message):
"""Tries to send an email using postfix local server
"""
ret = False
try:
logger.info("Trying to send emain using our local server.....")
smtp = smtplib.SMTP(timeout=10)
logger.info("Connected to our local smtp")
smtp.connect()
logger.info("Connected....OK")
smtp.sendmail(sender, recipients, message.as_string())
smtp.close()
ret = True
except Exception, e:
logger.error("An error occurred by sending email: %s" % str(e))
return ret
2.3、sendmail_using_relay_conf
邮件发送和smtp协议相关,首先启动smtp,然后输出提示信息或者报错。
def __sendmail_using_relay_conf(self, sender, recipients, message):
"""Tries to send an email using the relay info """
# Send the message via our own SMTP server.
ret = False
try:
smtp = smtplib.SMTP(self.__server, self.__port,timeout=10)
logger.info("Trying to send mail...Connection to the SMTP server..")
try:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
except smtplib.SMTPException: # STARTTLS not supported
pass
smtp.login(self.__user,self.__passwd)
logger.info("Connected to the smtp")
logger.info("Sending mail...")
smtp.sendmail(sender, recipients, message.as_string())
smtp.close()
ret = True
except Exception, e:
logger.error("An error occurred by sending email: %s" % str(e))
return ret
2.4、sendmail
发送邮件
MIMEText(message, 'plain', 'latin-1')
的plain,latin-1是设置文字内容格式。
Latin1是ISO-8859-1的别名,有些环境下写作Latin-1。 ISO-8859-1编码是单字节编码,向下兼容ASCII。
配置完邮件相关信息后,进行发送。
首先使用使用中继服务器发送电子邮件,失败后通过使用本地postfix来发送。
def sendmail(self, sender, recipients, subject, message):
# Create a text/plain message
msg = MIMEText(message, 'plain', 'latin-1')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ", ".join(recipients) if type(recipients) is list else recipients
ret = False
if self.__user == None or self.__user =="" or self.__user == "unconfigured":
self.__use_postfix = True
if self.__use_postfix:
ret = self.__sendmail_postfix(sender, recipients, msg)
else:
ret = self.__sendmail_using_relay_conf(sender, recipients, msg)
if not ret:
logger.info("Send the email using the relay server has failded. Trying it by using our local postfix..")
ret = self.__sendmail_postfix(sender, recipients, msg)
logger.info("Email sent ...... %s" % str(ret))