来自smtplib的附件文件 - python

时间:2017-02-14 09:42:55

标签: python base64 smtplib

我能够发送邮件。我计划将文件附加到smtplib.First的邮件转换为base64字符串,然后尝试从POST人员附加。 但它给出了以下错误“

  

MultipartConversionError:无法附加其他子部分   非多/ *

来自POST男子我发送如下

{
    "frommail":"ramesh.chowdaryxxx@gmail.com", 
    "password":"", 
    "tomail":"ramesh.xxxxx@xxxxxx.com",
    "subject":"Test Mail", 
    "message":"mail message here",
    "doctype":"",
    "docname":"",
    "document":"iVBORw0KGgoAAAANSUhEUgAAASoAAAEsCAYAAAB0Y/4yAAASfklEQVR4nO3df7BdVXXA8e9hMpkMgwylGeowlKGoFBFRU4ZSax1/0VpKrVqqIP6qdSpaRlE7olNLh7EttZaxaKfUWrQUEUEcpBR/R6EqYhWDQfkpIharCIQAMZCQZPWPfaMxebnvvvfuuWvfu7+fmTUvk5fMW2e/c9Y9Z"
}

如何修复此问题。我将base64字符串发送到“document”字段。

import smtplib
from email.mime.text import MIMEText as text
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
@csrf_exempt
@api_view(['POST']) 
def sendmail(request):
    if request.method == 'POST':
        data = request.data
        fromMail    =   data["frommail"]
        passwd      =   data["password"]
        toMail      =   data["tomail"]
        subject     =   data["subject"]
        text1       =   data["message"]
        doctype     =   data['doctype']
        docname     =   data['docname']
        document    =   data['document']

        msg = text(str(text1))
        msg['Subject'] = subject
        msg['From'] = fromMail
        msg['To'] = toMail

        part = MIMEBase('application', 'octet-stream')
        #part.set_payload(open(document, 'rb').read())
        #Encoders.encode_base64(part)
        part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(document))
        msg.attach(part)

        try:
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(fromMail, passwd)
            server.sendmail(fromMail, toMail, msg.as_string())
            server.quit()     
            return JSONResponse({"Status":"Successfully sent email"})
        except:
            return JSONResponse({"Failure":"Unable to send mail."})

1 个答案:

答案 0 :(得分:0)

尝试在代码中添加MIMEMultipart()。这应该可以解决你的问题。

attach file like object to email python 3

按照上述链接获取更多详细信息。