Pythonsend_mail()函数实现群发邮件的简便方法
发布时间:2024-01-10 10:27:54
Python提供了多种方式来发送邮件,其中一种是使用smtplib库。下面是一个简化群发邮件的例子,实现了一个Pythonsend_mail()函数:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
def Pythonsend_mail(smtp_server, smtp_port, sender, password, recipients, subject, message):
# 创建一个包含文本和附件的MIMEMultipart对象
msg = MIMEMultipart()
msg['From'] = Header(sender, 'utf-8')
msg['To'] = Header(','.join(recipients), 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
# 添加邮件正文
msg.attach(MIMEText(message, 'plain', 'utf-8'))
# 连接SMTP服务器
smtp = smtplib.SMTP(smtp_server, smtp_port)
smtp.starttls()
# 登录邮箱账号
smtp.login(sender, password)
try:
# 发送邮件
smtp.sendmail(sender, recipients, msg.as_string())
print("邮件发送成功")
except smtplib.SMTPException as e:
print("邮件发送失败")
print(str(e))
# 关闭连接
smtp.quit()
下面是使用这个函数发送邮件的例子:
smtp_server = 'smtp.example.com' # SMTP服务器地址 smtp_port = 587 # SMTP端口号 sender = 'sender@example.com' # 发件人邮箱 password = 'password' # 发件人邮箱密码 recipients = ['recipient1@example.com', 'recipient2@example.com'] # 收件人邮箱列表 subject = '群发邮件测试' # 邮件主题 message = '这是一封群发邮件的测试邮件' # 邮件内容 Pythonsend_mail(smtp_server, smtp_port, sender, password, recipients, subject, message)
在这个例子中,我们使用smtplib库创建了一个SMTP对象,并连接到SMTP服务器。然后,我们使用login()方法登录到发件人的邮箱账号。
接下来,我们创建了一个MIMEMultipart对象,该对象包含了邮件的文本和附件。我们设定了发件人、收件人、主题和邮件内容。然后,我们调用as_string()方法将MIMEMultipart对象转换为字符串,并调用sendmail()方法发送邮件。
最后,我们关闭SMTP连接。
注意,在使用这个函数发送邮件之前,需要确保你已经具备发送邮件的权限,并替换示例中的SMTP服务器地址、发件人邮箱和收件人邮箱等信息。
