您好,登錄后才能下訂單哦!
使用Python怎么實(shí)現(xiàn)郵件發(fā)送功能?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
# 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', '授權(quán)碼') # 注意,此處端口要用587,465端口是ssl使用的。 s.set_keepalive(False) s.set_debug(True) st = time.time() s.send('收信人郵箱地址', '測(cè)試', '測(cè)試郵件 From QQ') #要發(fā)送的賬號(hào)、標(biāo)題、內(nèi)容 print(time.time() - st)
看完上述內(nèi)容,你們掌握使用Python怎么實(shí)現(xiàn)郵件發(fā)送功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。