Search code examples
python-3.xmime-typessmtplibotrs

OTRS - REST-API - Send content of ticket including attachment via SMTPLIB


I am trying to get the content of a ticket via REST-API from OTRS v4 and send the content to an external mail-address.

Everything works fine, except the attachment part. It sends an attachment, but the file is not readable and even has a different size than the source.

Doc for OTRS REST-API (TicketGet): http://doc.otrs.com/doc/api/otrs/5.0/Perl/Kernel/GenericInterface/Operation/Ticket/TicketGet.pm.html

# get the data vie REST from OTRS

TicketID = "12345"

headers = {
    "Content-Type": 'application/json'
    }
payload = {
    'UserLogin': 'user',
    "Password": 'pass',
    "Extended": '1',
    'AllArticles': '1',
    'Attachments': '1',
}

url = 'https://somedomain.com/otrs/nph-genericinterface.pl/Webservice/GenericTicketConnectorREST/TicketGet/' + TicketID
result = requests.get(url, headers=headers, data=json.dumps(payload))
data = result.json()



# send content of ticket as an email to "soemone@somedmain.com"

email_subject = data['Ticket'][0]['Article'][0]['Subject']
email_body = data['Ticket'][0]['Article'][0]['Body']

msg = MIMEMultipart()
msg['From'] = "noreply@somedomain.com"
msg['To'] = "soemone@somedmain.com"
msg['Subject'] = email_subject

# text

msg.attach(MIMEText(email_body, 'plain'))


# attachment

attachment_content_type = data['Ticket'][0]['Article'][0]['Attachment'][0]['ContentType']  #outputs for example: 
attachment_content = data['Ticket'][0]['Article'][0]['Attachment'][0]['Content']         #base64 ?
attachment_filename = data['Ticket'][0]['Article'][0]['Attachment'][0]['Filename'] #outputs for example: 


mimetype = attachment_content_type.split(';')[0]
basetype, subtype = mimetype.split('/', 1)


att = MIMEBase(basetype, subtype)
att.set_payload(attachment_file)
att.add_header('Content-Disposition', 'attachment', filename=attachment_filename)
msg.attach(att)


# send msg

s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

Solution

  • Looks like this works:

    # attachment
    
    attachment_content = data['Ticket'][0]['Article'][0]['Attachment'][0]['Content']         
    attachment_filename = data['Ticket'][0]['Article'][0]['Attachment'][0]['Filename'] 
    
    
    filedata = base64.b64decode(attachment_content)
    
    att = MIMEBase('application', 'octet-stream')
    att.set_payload(filedata)
    encoders.encode_base64(att)
    att.add_header('Content-Disposition', 'attachment', filename=attachment_filename)
    
    msg.attach(att)
    
    
    # send msg
    
    s = smtplib.SMTP('localhost')
    s.send_message(msg)
    s.quit()