Python发送邮件功能示例【使用QQ邮箱】
程序员文章站
2022-04-04 14:49:13
本文实例讲述了python发送邮件功能。分享给大家供大家参考,具体如下:
这里以qq邮箱为例说明
登录邮箱点账号
开启smtp
开启时会要求你发送一条短信,...
本文实例讲述了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程序设计有所帮助。
上一篇: 【IT之家评测室】vivo X21屏幕指纹手机开箱上手视频
下一篇: 张柏芝出海游玩 手机壳亮了!