Python SMTP邮件发送的10个核心代码示例


【蜂邮EDM】:邮件群发系统,EDM邮件营销平台,邮件代发服务。 查看价格
【AokSend邮件API】:触发式邮件API,15元/万封,99%送达率。 查看价格
【烽火邮箱】:新人领取免费域名邮箱,可用作企业邮箱公司邮箱。 查看价格
Python SMTP邮件发送的10个核心代码示例
在现代系统中,邮件发送是一个非常重要且常见的任务。无论是企业内部沟通,还是个人项目,邮件都是信息传递的重要方式。而在Python中,通过python-multipart
和smtplib
库,可以轻松实现邮件发送功能。本文将介绍10个核心代码示例,帮助您快速掌握Python邮件发送的技巧。
引言
邮件发送作为常见的任务,在现代系统中无处不在。无论是企业内部沟通,还是个人项目,邮件都是信息传递的重要方式。而在Python中,通过python-multipart
和smtplib
库,可以轻松实现邮件发送功能。本文将介绍10个核心代码示例,帮助您快速掌握Python邮件发送的技巧。
邮件发送基础配置
在开始编写代码之前,我们需要先配置好环境。以下是一个基本的邮件发送配置示例:
import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText# 邮件配置server = 'smtp.example.com' # 邮局地址port = 587 # 邮局端口username = 'your_username' # 发件人邮箱用户名password = 'your_password' # 发件人邮箱密码use_tls = True # 使用TLS加密# recipients列表recipients = ['接收者1@example.com', '接收者2@example.com']# 邮件主题subject = '邮件主题'
发送单封邮件
# 创建MIMEMultipart对象msg = MIMEMultipart()msg.set_header('Subject', subject)msg.set_header('To', ', '.join(recipients))msg.set_header('From', username)# 添加正文内容text = "这是一封自动生成的邮件,主题是%s,内容如下:" % subjectbody = MIMEText(text, 'plain') # 设置编码为纯文本# 添加正文到邮件msg.attach(body)# 连接邮局server = smtplib.SMTP()if use_tls: server.connect(server, port=port)else: server.connect(server)# 发送邮件server.sendmail(username, recipients, msg.as_string())# 关闭连接server.quit()
批量发送邮件
import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText# 邮件配置server = 'smtp.example.com'port = 587username = 'your_username'password = 'your_password'use_tls = True# 批量发送邮件的接收者列表recipients_list = [ '接收者1@example.com', '接收者2@example.com', '接收者3@example.com']# 邮件主题subject = '邮件主题'# 发送时间send_time = '2023-10-01 10:00:00'# 正文内容text = "这是一封自动生成的邮件,主题是%s,内容如下:" % subjectbody = MIMEText(text, 'plain')# 创建MIMEMultipart对象msg = MIMEMultipart()msg['Subject'] = subjectmsg['To'] = ', '.join(recipients_list)msg['From'] = usernamemsg.set_header('Date', send_time)msg.attach(body)# 连接邮局server = smtplib.SMTP()if use_tls: server.connect(server, port=port)else: server.connect()# 发送邮件server.sendmail(username, recipients_list, msg.as_string())# 关闭连接server.quit()
邮件发送的邮件列表管理
import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport time# 邮件发送的接收者列表recipients = [ '接收者1@example.com', '接收者2@example.com', '接收者3@example.com']# 邮件主题subject = '邮件主题'# 发送时间间隔send_interval = 10 # 单位:分钟# 发送时间current_time = time.strftime('%Y-%m-%d %H:%M:%S')send_time = current_time + ' 10:00:00'# 正文内容text = "这是一封自动生成的邮件,主题是%s,内容如下:" % subjectbody = MIMEText(text, 'plain')# 创建MIMEMultipart对象msg = MIMEMultipart()msg['Subject'] = subjectmsg['To'] = ', '.join(recipients)msg['From'] = 'your_username@example.com'msg.set_header('Date', send_time)msg.attach(body)# 连接邮局server = smtplib.SMTP()server.connect('smtp.example.com', 587)server.starttls() # 使用TLSserver.login('your_username@example.com', 'your_password') # 登录# 发送邮件server.sendmail('your_username@example.com', recipients, msg.as_string())# 等待下一个发送时间time.sleep(send_interval)# 关闭连接server.quit()
附件添加到邮件
import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email附件添加到邮件 MIMEMultipart import MIMEBase# 邮件发送的接收者列表recipients = ['接收者1@example.com', '接收者2@example.com']# 邮件主题subject = '邮件主题'# 正文内容text = "这是一封自动生成的邮件,主题是%s,内容如下:" % subjectbody = MIMEText(text, 'plain')# 附件信息attachment_path = 'C:/document/附件1.pdf'attachment_name = '附件1.pdf'attachment_type = 'application/pdf'# 创建MIMEMultipart对象msg = MIMEMultipart()msg['Subject'] = subjectmsg['To'] = ', '.join(recipients)msg['From'] = 'your_username@example.com'msg.set_header('Date', time.strftime('%Y-%m-%d %H:%M:%S'))# 添加正文到邮件msg.attach(body)# 添加附件with open(attachment_path, 'rb') as f: attachment = MIMEBase('application/octet-stream', name=attachment_name, type=attachment_type) attachment.set_header('Content-Disposition', f'inline; filename="{attachment_name}"') attachment.set_header('Content-Type', attachment_type) attachment.set_header('Content-Disposition', f'attachment; filename="{attachment_name}"') msg.attach(attachment)# 连接邮局server = smtplib.SMTP()server.connect('smtp.example.com', 587)server.starttls()server.login('your_username@example.com', 'your_password')# 发送邮件server.sendmail('your_username@example.com', recipients, msg.as_string())# 关闭连接server.quit()
邮件发送的邮件日志记录
import smtplibimport logging# 邮件发送日志记录的配置logging.basicConfig(filename='smtp_email.log', level=logging.INFO)# 邮件发送的接收者列表recipients = ['接收者1@example.com', '接收者2@example.com']# 邮件主题subject = '邮件主题'# 发送时间send_time = time.strftime('%Y-%m-%d %H:%M:%S')# 正文内容text = "这是一封自动生成的邮件,主题是%s,内容如下:" % subjectbody = MIMEText(text, 'plain')# 创建MIMEMultipart对象msg = MIMEMultipart()msg['Subject'] = subjectmsg['To'] = ', '.join(recipients)msg['From'] = 'your_username@example.com'msg.set_header('Date', send_time)msg.attach(body)# 设置日志记录logger = logging.getLogger(__name__)logger.info(msg)# 连接邮局server = smtplib.SMTP()server.connect('smtp.example.com', 587)server.starttls()server.login('your_username@example.com', 'your_password')# 发送邮件server.sendmail('your_username@example.com', recipients, msg.as_string())# 关闭连接server.quit()
邮件发送的错误处理
import smtplibimport logging# 邮件发送日志记录的配置logging.basicConfig(filename='smtp_email.log', level=logging.INFO)try: # 邮件发送的接收者列表 recipients = ['接收者1@example.com', '接收者2@example.com'] # 邮件主题 subject = '邮件主题' # 发送时间 send_time = time.strftime('%Y-%m-%d %H:%M:%S') # 正文内容 text = "这是一封自动生成的邮件,主题是%s,内容如下:" % subject body = MIMEText(text, 'plain') # 创建MIMEMultipart对象 msg = MIMEMultipart() msg['Subject'] = subject msg['To'] = ', '.join(recipients) msg['From'] = 'your_username@example.com' msg.set_header('Date', send_time) msg.attach(body) # 连接邮局 server = smtplib.SMTP() server.connect('smtp.example.com', 587) server.starttls() server.login('your_username@example.com', 'your_password') # 发送邮件 server.sendmail('your_username@example.com', recipients, msg.as_string()) logger.info(msg)except smtplib.SMTPException as e: logger.error(f"邮件发送失败:{e}") print(f"邮件发送失败:{e}")except Exception as e: logger.error(f"邮件发送过程中出现异常:{e}") print(f"邮件发送过程中出现异常:{e}")finally: server.quit()
邮件发送的性能优化
import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText# 邮件发送的接收者列表recipients = ['接收者1@example.com', '接收者2@example.com', '接收者3@example.com']# 邮件主题subject = '邮件主题'# 发送时间current_time = time.strftime('%Y-%m-%d %H:%M:%S')send_time = current_time + ' 10:00:00'# 正文内容text = "这是一封自动生成的邮件,主题是%s,内容如下:" % subjectbody = MIMEText(text, 'plain')# 创建MIMEMultipart对象msg = MIMEMultipart()msg['Subject'] = subjectmsg['To'] = ', '.join(recipients)msg['From'] = 'your_username@example.com'msg.set_header('Date', send_time)msg.attach(body)# 连接邮局server = smtplib.SMTP()server.connect('smtp.example.com', 587)server.starttls()server.login('your_username@example.com', 'your_password')# 发送邮件server.sendmail('your_username@example.com', recipients, msg.as_string())# 关闭连接server.quit()
邮件发送的统计分析
import smtplibimport pandas as pd# 邮件发送的接收者列表recipients = ['接收者1@example.com', '接收者2@example.com', '接收者3@example.com']# 邮件主题subject = '邮件主题'# 发送时间send_time = time.strftime('%Y-%m-%d %H:%M:%S')# 正文内容text = "这是一封自动生成的邮件,主题是%s,内容如下:" % subjectbody = MIMEText(text, 'plain')# 创建MIMEMultipart对象msg = MIMEMultipart()msg['Subject'] = subjectmsg['To'] = ', '.join(recipients)msg['From'] = 'your_username@example.com'msg.set_header('Date', send_time)msg.attach(body)# 连接邮局server = smtplib.SMTP()server.connect('smtp.example.com', 587)server.starttls()server.login('your_username@example.com', 'your_password')# 发送邮件server.sendmail('your_username@example.com', recipients, msg.as_string())# 关闭连接server.quit()# 收集邮件发送数据email_data = { '发送时间': [send_time], '接收者': recipients, '主题': [subject], '正文': [text]}# 将数据转换为DataFramedf = pd.DataFrame(email_data)# 保存到CSV文件df.to_csv('email_stats.csv', index=False)
邮件发送的测试
import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText# 邮件发送的接收者列表recipients = ['接收者1@example.com', '接收者2@example.com']# 邮件主题subject = '邮件主题'# 发送时间send_time = time.strftime('%Y-%m-%d %H:%M:%S')# 正文内容text = "这是一封自动生成的邮件,主题是%s,内容如下:" % subjectbody = MIMEText(text, 'plain')# 创建MIMEMultipart对象msg = MIMEMultipart()msg['Subject'] = subjectmsg['To'] = ', '.join(recipients)msg['From'] = 'your_username@example.com'msg.set_header('Date


【蜂邮EDM】:邮件群发系统,EDM邮件营销平台,邮件代发服务。 查看价格
【AokSend邮件API】:触发式邮件API,15元/万封,99%送达率。 查看价格
【烽火邮箱】:新人领取免费域名邮箱,可用作企业邮箱公司邮箱。 查看价格
【烽火邮箱】:烽火邮箱是一款简洁高效的企业邮箱平台,新客户赠送免费企业邮箱,一个起卖、按月付费(低至9.9元);支持别名邮箱及群组邮箱,支持定制无限邮箱。高权重纯净IP池,系统自带反垃圾机制。
立即查看 >> :企业邮箱价格
【蜂邮EDM】:邮件群发系统,EDM邮件营销平台,邮件代发服务,专业研发定制邮件营销系统及邮件群发解决方案!蜂邮自研产品线主要分为标准版、外贸版、企业版、定制版,及邮件API邮件SMTP接口服务。
立即查看 >> :邮件发送价格
【AokSend邮件API】:专注触发式邮件API发送服务。15元/万封,发送验证码邮件、忘记密码邮件、通知告警邮件等,不限速。综合送达率99%、进箱率98%。触发邮件也叫事务性邮件或推送邮件,包含:验证码邮件、重置密码邮件、余额提醒邮件、会员到期邮件、账号认证邮件等!
立即查看 >> :邮件发送价格