这里是详细讲解“python实现自动发送邮件发送多人、群发、多附件的示例”的完整攻略。
1. 准备工作
首先,我们需要在本地安装Python并使用pip安装必要的库,如smtplib和email,用于连接SMTP服务器和构建邮件。另外,还需要进行一些邮箱的设置,例如开启SMTP服务等。
2. 发送基本邮件
我们可以通过以下代码发送一封基本的邮件:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 发送人邮箱
sender = 'your_email@example.com'
# 接收人邮箱
receiver = 'to_email@example.com'
# 邮件主题
subject = 'Python SMTP 邮件测试'
# 邮件内容
content = '这是一封使用Python发送的邮件。'
# 构建邮件
message = MIMEText(content, 'plain', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(receiver, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
# 发送邮件
smtpObj = smtplib.SMTP('smtp.example.com', 25)
smtpObj.login(sender, 'password')
smtpObj.sendmail(sender, receiver, message.as_string())
print('邮件发送成功!')
3. 发送多人邮件
如果想要发送邮件给多个人,我们可以把收件人的邮箱地址保存在一个列表中,然后遍历列表发送邮件:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 发送人邮箱
sender = 'your_email@example.com'
# 接收人邮箱列表
receivers = ['to_email_1@example.com', 'to_email_2@example.com']
# 邮件主题
subject = 'Python SMTP 邮件测试'
# 邮件内容
content = '这是一封使用Python发送的邮件。'
# 构建邮件
message = MIMEText(content, 'plain', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(','.join(receivers), 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
# 发送邮件
smtpObj = smtplib.SMTP('smtp.example.com', 25)
smtpObj.login(sender, 'password')
smtpObj.sendmail(sender, receivers, message.as_string())
print('邮件发送成功!')
4. 发送带附件邮件
有时候,我们需要发送带附件的邮件。这时,我们需要使用MIMEMultipart和MIMEApplication来构建邮件。下面是一个示例代码,用于发送一封带附件的邮件:
import os
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 发送人邮箱
sender = 'your_email@example.com'
# 接收人邮箱
receiver = 'to_email@example.com'
# 邮件主题
subject = 'Python SMTP 邮件测试'
# 邮件内容
content = '这是一封使用Python发送的带附件的邮件。'
# 构建邮件
message = MIMEMultipart()
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(receiver, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
message.attach(MIMEText(content, 'plain', 'utf-8'))
# 添加附件
# 文件路径需要根据实际情况修改
file_path1 = 'attachment1.txt'
file_path2 = 'attachment2.txt'
att1 = MIMEApplication(open(file_path1, 'rb').read())
att1.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_path1))
message.attach(att1)
att2 = MIMEApplication(open(file_path2, 'rb').read())
att2.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_path2))
message.attach(att2)
# 发送邮件
smtpObj = smtplib.SMTP('smtp.example.com', 25)
smtpObj.login(sender, 'password')
smtpObj.sendmail(sender, receiver, message.as_string())
print('邮件发送成功!')
以上便是使用Python发送邮件的示例说明,希望能够对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python实现自动发送邮件发送多人、群发、多附件的示例 - Python技术站