我编写了以下适用于我的实用程序类:
import ssl
import smtplib
from email.message import EmailMessage
class Email:
def __init__(self, server: str, port: int, address: str, password: str | None):
self.server = server
self.port = port
self.address = address
self.password = password
def send_email(
self, mail_to: str | list, subject: str, body: str, html: bool = False, use_ssl: bool = True
) -> None:
"""
sending the email
Args:
mail_to: receiver, can be a list of strings
subject: the subject of the email
body: the body of the email
html: whether the body is formatted with html or not
use_ssl: whether to use a secure ssl connection and authentication
Returns:
None
"""
if not isinstance(mail_to, str):
mail_to = ', '.join(mail_to)
if self.server == 'localhost':
with smtplib.SMTP(self.server, self.port) as server:
message = f'Subject: {subject}\n\n{body}'
server.sendmail(self.address, mail_to, message)
return None
else:
mail = EmailMessage()
mail['Subject'] = subject
mail['From'] = self.address
mail['To'] = mail_to
if html:
mail.add_alternative(body, subtype='html')
else:
mail.set_content(body)
if use_ssl:
with smtplib.SMTP_SSL(self.server, self.port, context=ssl.create_default_context()) as server:
server.login(self.address, self.password)
server.send_message(mail)
else:
with smtplib.SMTP(self.server, self.port) as server:
server.send_message(mail)
return None
你可以像这样使用它:
my_email = Email(server='localhost', port=1025, address='sender@example.com', password='password')
my_email.send_email(
mail_to=['receiver1@example.com', 'receiver2@example.com'],
subject='Email Subject',
body='Email Body',
html=False,
use_ssl=False,
)
这是一个使用 python 调试服务器可视化电子邮件的示例,但实际上并未发送它们。它对于测试目的非常有用。要启动调试服务器,只需在终端或 Windows cli(例如命令提示符或 powershell)中键入 python -m smtpd -c DebuggingServer -n localhost:1025。
要发送真正的电子邮件,只需将参数server 和port 替换为实际值,如果需要,还可以选择使用标志html 和use_ssl。