使用Python中的MIMEText邮件发送带有抄送人的邮件
发布时间:2023-12-11 13:48:58
发送带有抄送人的邮件可以使用Python中的smtplib和email库。首先,需要导入相应的模块:
import smtplib from email.mime.text import MIMEText from email.header import Header
接下来,可以设置邮件内容和邮件头信息:
# 发送方邮箱
sender = 'example_sender@example.com'
# 接收方邮箱
receivers = ['example_receiver1@example.com', 'example_receiver2@example.com']
# 抄送人邮箱
cc = ['example_cc1@example.com', 'example_cc2@example.com']
# 创建一个带有邮件内容和邮件头信息的MIMEText对象
message = MIMEText('邮件内容', 'plain', 'utf-8')
message['From'] = Header("发件人姓名", 'utf-8')
message['To'] = Header("接收人姓名", 'utf-8')
message['Cc'] = ','.join(cc)
然后,需要登录发送邮箱的SMTP服务器,并设置发送方邮箱和密码:
# 发送方邮箱登录的SMTP服务器地址 smtp_server = 'smtp.example.com' # 发送方邮箱登录的SMTP服务器端口 smtp_port = 25 # 发送方邮箱用户名和密码 smtp_user = 'example_sender@example.com' smtp_password = 'password'
接下来,可以通过smtplib模块发送邮件:
# 创建SMTP对象 smtp_obj = smtplib.SMTP(smtp_server, smtp_port) # 开启安全连接 smtp_obj.starttls() # 登录SMTP服务器 smtp_obj.login(smtp_user, smtp_password) # 发送邮件 smtp_obj.sendmail(sender, receivers+cc, message.as_string()) # 关闭SMTP连接 smtp_obj.quit()
下面是完整的示例代码:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 发送方邮箱
sender = 'example_sender@example.com'
# 接收方邮箱
receivers = ['example_receiver1@example.com', 'example_receiver2@example.com']
# 抄送人邮箱
cc = ['example_cc1@example.com', 'example_cc2@example.com']
# 创建一个带有邮件内容和邮件头信息的MIMEText对象
message = MIMEText('邮件内容', 'plain', 'utf-8')
message['From'] = Header("发件人姓名", 'utf-8')
message['To'] = Header("接收人姓名", 'utf-8')
message['Cc'] = ','.join(cc)
# 发送方邮箱登录的SMTP服务器地址
smtp_server = 'smtp.example.com'
# 发送方邮箱登录的SMTP服务器端口
smtp_port = 25
# 发送方邮箱用户名和密码
smtp_user = 'example_sender@example.com'
smtp_password = 'password'
# 创建SMTP对象
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
# 开启安全连接
smtp_obj.starttls()
# 登录SMTP服务器
smtp_obj.login(smtp_user, smtp_password)
# 发送邮件
smtp_obj.sendmail(sender, receivers+cc, message.as_string())
# 关闭SMTP连接
smtp_obj.quit()
使用这段示例代码,可以实现发送带有抄送人的邮件。需要替换示例代码中的发件人邮箱、接收人邮箱、抄送人邮箱、发件人姓名、接收人姓名、邮件内容、SMTP服务器信息以及登录信息,以符合实际需求。
