我正在尝试将压缩文件夹作为电子邮件附件从 gmail 帐户发送到 gmail 帐户。
我发送简单的 .txt 文件时没有问题,但是无论我使用什么压缩类型,我都无法成功发送压缩文件。即使我压缩了一个文件,当我从 Gmail 下载回来时,它也会损坏。我已经尝试了几件事,比如先加密文件ccrypt
然后发送。该文件仍然损坏。
如果我从浏览器正常发送带有相同附件的电子邮件,则这不适用。这让我想知道是 Gmail 还是我用来责备的代码。
这是我的代码:
#!/usr/bin/python
import os, re
import sys
import smtplib
from email import encoders
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.MIMEText import MIMEText
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = 'email@gmail.com'
password = "password"
recipient = sys.argv[1]
subject = ''
message = sys.argv[3]
def main():
msg = MIMEMultipart()
msg['Subject'] = sys.argv[2]
msg['To'] = recipient
msg['From'] = sender
part = MIMEText('text', "plain")
part.set_payload(message)
msg.attach(part)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)
fp = open(sys.argv[4], 'rb')
msgq = MIMEBase('application', "octet-stream")
msgq.set_payload(fp.read())
fp.close()
# Encode the payload using Base64
filename=sys.argv[4]
msgq.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(msgq)
# Now send or store the message
qwertyuiop = msg.as_string()
session.sendmail(sender, recipient, qwertyuiop)
session.quit()
if __name__ == '__main__':
main()
它被用作:
./send_email.py receiver@gmail.com "title" "body" attachment.rar
您应该在脚本顶部填写您的登录详细信息。