发送邮件代码如下:
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import datetime
from poseidon.myutil import MyUtil
import logging
from _socket import timeout
class SendMail:
'''
发送邮件
‘发件服务器地址’、‘发件服务器端口’,‘是否使用ssl加密’
'''
def __init__(self, smtpServer, port, isSSL):
self.logger = logging.getLogger('myLogger.mail.SendMail')
self.smtpServer = smtpServer
self.port = port
self.isSSL = isSSL == 'True'
self.logger.info('%s %s %s' % (self.smtpServer, self.port, self.isSSL))
def send(self, content, sendto, title):
'''
发送邮件
@param content: 邮件内容
@param sendto: 收件人,多个收件人以','分割
@param title:邮件标题
@return: True,发送成功;否则,False
'''
todayStr = datetime.datetime.now().strftime('%Y-%m-%d')
msg = MIMEText(content, 'html', 'utf-8')
fromUser = MyUtil.loadProperty('mail', 'from')
password = MyUtil.loadProperty('mail', 'password')
mailTitle = '%s%s' % (todayStr, title)
self.logger.info(' from:%s to:%s title:%s' % (fromUser, sendto, mailTitle))
msg['From'] = Header(u'%s' % fromUser)
msg['To'] = Header(u'%s' % sendto)
msg['Subject'] = Header(u'%s' % mailTitle, 'utf-8').encode()
if self.isSSL:
server = smtplib.SMTP_SSL(self.smtpServer, self.port, timeout=20)
else:
server = smtplib.SMTP(self.smtpServer, self.port, timeout=20)
# 开启debug日志
server.set_debuglevel(1)
server.login(fromUser, password)
server.sendmail(fromUser, sendto.split(','), msg.as_string())
server.quit()
if __name__ == '__main__':
MyUtil('../../../config.properties')
sm = SendMail('smtp.exmail.qq.com', 465, 'True')
sm.send('hello buddy!','aaa@163.com', 'hello')
config.properties中需要配置
[mail]
#邮箱发送账户
from=aaa@qq.com
#发送账户密码
password=bbb
#发件服务器
smtp=smtp.exmail.qq.com
#发件服务器端口
port=465
#是否加密传输
isSSL=True
参考文章: SMTP发送邮件--廖雪峰