有一次,小明需要给公司所有同事发送一封感谢邮件,他编写了一个Python脚本,一键实现批量发送邮件,省时又高效!
代码语言:javascript复制import smtplib
from email.mime.text import MIMEText
def send_email(to, subject, content):
设置发件人、收件人、邮件主题和内容
sender = 'example@gmail.com'
receivers = to
message = MIMEText(content)
message['Subject'] = subject
message['From'] = sender
message['To'] = ', '.join(receivers)
发送邮件
try:
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.starttls()
smtpObj.login('your_email', 'your_password')
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
print('邮件发送成功')
except smtplib.SMTPException:
print('邮件发送失败')
使用示例
to = ['colleague1@example.com', 'colleague2@example.com']
subject = '感谢邮件'
content = '大家辛苦了,感谢你们的付出!'
send_email(to, subject, content)