我正在尝试将压缩文件夹作为电子邮件附件从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
您应该在脚本之上填写您的登录详细信息。
答案 0 :(得分:2)
评论# Encode the payload using Base64
后,请尝试此操作... encoders.encode_base64(msgq)