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

时间:2022-05-22 23:16:53

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

这里以qq邮箱为例说明

登录邮箱点账号

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

开启smtp

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

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

就有授权码了

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 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程序设计有所帮助。

原文链接:https://blog.csdn.net/Yort2016/article/details/75109854