python smtplib 发送邮件设置抄送人
时间: 2023-11-08 10:53:51 浏览: 106
好的,以下是 python smtplib 发送邮件设置抄送人的代码示例:
```python
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 设置邮件发送方,接收方,抄送方及内容
sender = 'from@example.com'
receivers = ['to@example.com']
cc = ['cc@example.com']
mail_content = 'Hello, this is a test email.'
message = MIMEText(mail_content, 'plain', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(receivers[0], 'utf-8')
message['Cc'] = ','.join(cc)
message['Subject'] = Header('Test Email', 'utf-8')
# 设置邮件服务器及账户信息
smtp_server = 'smtp.example.com'
smtp_port = 25
smtp_username = 'username'
smtp_password = 'password'
# 发送邮件
try:
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
smtp_obj.login(smtp_username, smtp_password)
smtp_obj.sendmail(sender, receivers + cc, message.as_string())
print('邮件发送成功')
except smtplib.SMTPException as e:
print('邮件发送失败:', e)
```
以上代码中,抄送人信息存储在 cc 列表中,可以通过 `message['Cc'] = ','.join(cc)` 设置抄送人信息。smtp_server、smtp_port、smtp_username 和 smtp_password 分别代表邮件服务器、邮件服务器端口、邮件账户名和邮件账户密码,需要根据实际情况进行修改。
阅读全文