python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python发送邮件

Python发送邮件功能示例【使用QQ邮箱】

作者:Yort2016

这篇文章主要介绍了Python发送邮件功能,结合实例形式分析了Python使用QQ邮箱进行邮件发送的相关设置与使用技巧,需要的朋友可以参考下

本文实例讲述了Python发送邮件功能。分享给大家供大家参考,具体如下:

这里以QQ邮箱为例说明

登录邮箱点账号

开启smtp

开启时会要求你发送一条短信,发送完成后点已发送。

就有授权码了

代码如下,只需更改发件人、收件人等信息即可

# 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相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:
阅读全文