0

I am able to send the mail.I am planing to attach the file to mail from smtplib.First converted to base64 string and then trying to attach from the POST man. But its giving the below error "

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

from POST man i am sending like below

{
    "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"
}

How to fix this.Here i am sending the base64 string to "document" field.

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."})
user1335606
  • 479
  • 2
  • 5
  • 14

1 Answers1

0

Try to add MIMEMultipart() in your code. That should solve your problem.

attach file like object to email python 3

Follow the above link to get in more detail.

Community
  • 1
  • 1
Venkatesh_CTA
  • 120
  • 10