您好,登錄后才能下訂單哦!
這篇文章主要介紹了Python如何發送郵件,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
一、郵件發送示例
郵件發送示例
flask_email及smtplib原生郵件發送示例,適用于基于Flask框架開發,但是內部設置的定時任務發送郵件/或提供離線接口發送郵件操作
1.flask config配置
# QQ郵箱配置 MAIL_DEBUG = True # 開啟debug,便于調試看信息 MAIL_SUPPRESS_SEND = False # 發送郵件,為True則不發送 MAIL_SERVER = 'smtp.qq.com' # 郵箱服務器 MAIL_PORT = 465 # 端口 MAIL_USE_SSL = True # 重要,qq郵箱需要使用SSL MAIL_USE_TLS = False # 不需要使用TLS MAIL_USERNAME = '@qq.com' # 填郵箱 MAIL_PASSWORD = '' # 填授權碼 FLASK_MAIL_SENDER = '@qq.com' # 郵件發送方 FLASK_MAIL_SUBJECT_PREFIX = '' # 郵件標題 MAIL_DEFAULT_SENDER = '@qq.com' # 填郵箱,默認發送者
2.示例代碼
import smtplib import constant # 定義常量文件 from email.header import Header from email.mime.text import MIMEText constant.SMTP_SERVER = 'smtp.qq.com' constant.PORT = 465 class EmailSender(object): def __init__(self, subject, receivers, sender='ss@qq.com', password='123456', offline=False, html_body=None, text_body=None, **kwargs): self.subject = subject self.receivers = receivers self.sender = sender self.password = password if offline: if html_body: self.send_body = html_body self._subtype = 'html' elif text_body: self.send_body = text_body self._subtype = 'plain' self.send_email_offline() else: from flask_mail import Mail self.mail = Mail() dic = dict(kwargs) self.send_email(html_body, text_body, attachments=dic.get("attachments"), sync=dic.get("sync")) def send_email_offline(self): try: message = MIMEText(self.send_body, self._subtype, 'utf-8') message['From'] = self.sender message['To'] = ','.join(self.receivers) message['Subject'] = Header(self.subject, 'utf-8') smtpObj = smtplib.SMTP_SSL(constant.SMTP_SERVER, constant.PORT) smtpObj.login(self.sender, self.password) smtpObj.sendmail( self.sender, self.receivers, message.as_string()) smtpObj.quit() except smtplib.SMTPException: return "smtp服務器發送異常 >> 無法發送郵件" except Exception as e: return f"郵件發送失敗 >> {e}" def send_email(self, text_body, html_body, attachments=None, sync=False): from threading import Thread from flask import current_app from flask_mail import Message try: msg = Message(self.subject, recipients=self.receivers) msg.body = text_body msg.html = html_body if attachments: for attachment in attachments: msg.attach(*attachment) if not sync: self.mail.send(msg) else: Thread(target=self.send_async_email, args=(current_app._get_current_object(), msg)).start() except Exception as e: return f"郵件發送失敗 >> {e}" def send_async_email(self, app, msg): with app.app_context(): try: self.mail.send(msg) except Exception as e: print(f"郵件發送錯誤信息:{e}")
3.使用
err = EmailSender(subject='吃貨詢問', receivers=["123@qq.com", "1234@qq.cn"], text_body='吃了沒呀?', offline=True) if err: print(err)
感謝你能夠認真閱讀完這篇文章,希望小編分享的“Python如何發送郵件”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。