您好,登錄后才能下訂單哦!
使用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。