来自 smtplib 的附加文件 - python

Attache file from smtplib - python

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

MultipartConversionError: Cannot attach additional subparts to non-multipart/*

来自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"
}

如何修复 this.Here 我正在将 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."})

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

按照上述link了解更多详情。