python 用公共邮箱发信 发送gzip附件写法
时间: 2023-08-26 18:56:03 浏览: 110
在Python中使用公共邮箱发送带有gzip压缩附件的邮件,你可以使用`email`和`smtplib`库来实现。下面是一个示例代码:
```python
import smtplib
import os
import gzip
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
def send_email_with_gzip_attachment(sender_email, sender_password, receiver_email, subject, message, attachment_path):
# 创建邮件对象
msg = MIMEMultipart()
# 设置邮件主题、正文和收件人
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email
# 添加正文
msg.attach(MIMEText(message, 'plain'))
# 压缩附件
with open(attachment_path, 'rb') as f_in:
with gzip.open(attachment_path + '.gz', 'wb') as f_out:
f_out.writelines(f_in)
# 添加压缩后的附件
attachment = MIMEBase('application', 'gzip')
attachment.set_payload(open(attachment_path + '.gz', 'rb').read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment_path + '.gz'))
msg.attach(attachment)
try:
# 连接到邮箱服务器并发送邮件
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
server.quit()
print("邮件发送成功!")
except Exception as e:
print("邮件发送失败:", str(e))
# 设置发件人邮箱和密码
sender_email = 'your_email@gmail.com'
sender_password = 'your_password'
# 设置收件人邮箱、邮件主题、正文和附件路径
receiver_email = 'recipient_email@gmail.com'
subject = '测试邮件'
message = '这是一封带有gzip附件的测试邮件'
attachment_path = 'path_to_your_attachment.txt'
# 发送邮件
send_email_with_gzip_attachment(sender_email, sender_password, receiver_email, subject, message, attachment_path)
```
确保将`your_email@gmail.com`和`your_password`替换为实际的发件人邮箱和密码,`recipient_email@gmail.com`替换为收件人邮箱,`path_to_your_attachment.txt`替换为实际的附件路径。
这段代码会将指定的附件进行gzip压缩,并作为gzip类型的附件添加到邮件中发送出去。
阅读全文