Last active
September 3, 2024 13:46
-
-
Save ixuuux/d54b170b729702167419a9293bcd246e to your computer and use it in GitHub Desktop.
在Python中发送邮件,不依赖其他第三方库
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
File Name : send_mail.py | |
Create Date : 2020/10/24 15:26 | |
""" | |
import threading | |
import smtplib | |
from email.mime.text import MIMEText | |
class SendMail: | |
""" 封装发送邮件 """ | |
_instance = None | |
def __new__(cls, *args, **kwargs): | |
if cls._instance is None: | |
cls._instance = object.__new__(cls) | |
return cls._instance | |
def __init__(self, smtpsever: str, sender: str, sender_pwd: str, to_email: str): | |
""" 初始化 | |
:param smtpsever: smtp服务器地址,比如163的为smtp.163.com | |
:param sender: 发信者的邮箱地址 | |
:param sender_pwd: 发信者的邮箱密码(授权码) | |
:param to_email: 收信者邮箱地址 | |
""" | |
self.smtpsever = smtpsever | |
self.sender = sender | |
self.sender_pwd = sender_pwd | |
self.to_email = to_email | |
self._smtp = None # type: smtplib.SMTP | |
def login(self) -> smtplib.SMTP: | |
""" 登录发信者 """ | |
smtp = smtplib.SMTP() | |
smtp.connect(self.smtpsever) | |
smtp.login(self.sender, self.sender_pwd) | |
self._smtp = smtp | |
print('login') | |
return smtp | |
def send(self, title: str, text: str, to_mail: str=None, _try_again_login: bool=True) -> bool: | |
""" 发送邮件 | |
:param title: 邮件标题 | |
:param text: 邮件内容 | |
:param to_mail: 发送给谁,可选的,如果为None,那么将发送给初始化时定义的收信者 | |
:param _try_again_login: 由于放置时间过长登录状态会掉,是否进行重新登录 | |
:return: | |
""" | |
if self._smtp is None: | |
self.login() | |
msg = MIMEText(text, 'html', 'utf-8') | |
msg['from'] = self.sender | |
msg['to'] = to_mail or self.to_email | |
msg['subject'] = title | |
try: | |
self._smtp.sendmail( | |
from_addr=self.sender, | |
to_addrs=to_mail or self.to_email, | |
msg=msg.as_string() | |
) | |
return True | |
except Exception as e: | |
if _try_again_login: | |
self.login() | |
return self.send(title=title, text=text, to_mail=to_mail, _try_again_login=False) | |
return False | |
def send_in_thread(self, title: str, text: str, to_mail: str=None): | |
""" 在新线程中发送邮件,不阻塞当前操作 """ | |
threading.Thread( | |
target=self.send, | |
args=[title, text, to_mail] | |
).start() | |
if __name__ == '__main__': | |
s = SendMail(smtpsever='smtp.163.com', sender='发件人@163.com', sender_pwd='发件人密码/授权码', to_email='收件人@qq.com') | |
s.send_in_thread('title', 'text', to_mail='收件人@126.com') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment