使用Python怎么实现邮件发送功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
# encoding: utf-8 import logging import smtplib from email.mime.text import MIMEText import email.utils from datetime import datetime _logger = logging.getLogger('utils.mailclient') class MailClient(object): def __init__(self, host, port, user, pwd=''): self._host = host self._port = port self._user = user self._pwd = pwd self._smtp_server = None self._debug = False self._keepalive = True def set_keepalive(self, keepalive): self._keepalive = keepalive def set_debug(self, debug): self._debug = debug if self._smtp_server is not None: self._smtp_server.set_debuglevel(self._debug) def _connect(self): if self._smtp_server is None: _smtp_server = smtplib.SMTP(self._host, self._port) _smtp_server.ehlo() _smtp_server.starttls() _smtp_server.set_debuglevel(self._debug) if self._pwd: _smtp_server.login(self._user, self._pwd) self._smtp_server = _smtp_server return self._smtp_server def _dispose(self): if self._smtp_server is not None: self._smtp_server.quit() self._smtp_server = None def send(self, to_addrs, subject, content, isdispose=True): _smtp_server = self._connect() if not isinstance(to_addrs, list): to_addrs = [to_addrs] _msg = MIMEText(content, 'html', 'utf-8') _msg['Subject'] = subject _msg['From'] = self._user _msg['To'] = '; '.join(to_addrs) _msg['Date'] = datetime.now().strftime('%Y-%d-%m %H:%M:%S') _smtp_server.sendmail(self._user, to_addrs, _msg.as_string()) isdispose and (not self._keepalive) and self._dispose() def send_mails(self, mails): _smtp_server = self._connect() for mail in mails: self._send_mail(mail.get('to'), mail.get('subject'), mail.get('content'), False) (not self._keepalive) and self._dispose() def close(self): self._dispose() if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S') import time s = MailClient('smtp.qq.com', 587, '10010@qq.com', '授权码') # 注意,此处端口要用587,465端口是ssl使用的。 s.set_keepalive(False) s.set_debug(True) st = time.time() s.send('收信人邮箱地址', '测试', '测试邮件 From QQ') #要发送的账号、标题、内容 print(time.time() - st)
看完上述内容,你们掌握使用Python怎么实现邮件发送功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。