I'm trying to develop a Mule application with inbound IMAP connector. It works fine when the incoming mail is plain text but when it's HTML or Rich Text there's no text in the payload. How to make the application independent of the incoming mail type?
HTML or Rich Text are most probably MIME multipart emails. In that case, Mule tries to extract the text has payload only if the multipart email contains a first part that is has a content type starting with text/ (like text/plain). I reckon that in your case, the multipart email doesn't match this rule, thus Mule doesn't know what to do with it.
I suggest you use a choice router to deal with the case when there's no text in the payload after the email has been received. In that case, use whatever logic that is relevant to you to extract the content from one of the inbound attachments into which the different parts have been transferred.
I've been able to write some Java-code that bring out the text-part of a multipart message but I can't find a way to get this working with Mule. MUle wants to load the class with a String even though it's a multi part message.
The code I've written is below:
import javax.activation.DataHandler;
import javax.mail.*;
public class ReadMultipartMail3 {
public String stringback(Part payload) throws Exception {
String answer ="";
if(payload.isMimeType("text/plain") || payload.isMimeType("text/html"))
{
answer=(payload.getContent().toString());
}
else{
Multipart multipart = (Multipart) payload.getContent();
for (int x = 0; x < multipart.getCount(); x++) {
Part p = multipart.getBodyPart(x);
System.out.println("Content Type: "+p.getContentType());
BodyPart bodyPart = multipart.getBodyPart(x);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
System.out.println("Mail have some attachment : ");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
} else {
if(p.isMimeType("text/plain") || p.isMimeType("text/html"))
{
answer = (p.getContent().toString());
}
else if (p.isMimeType("multipart/alternative"))
{
Multipart mp = (Multipart)p.getContent();
int partsCount = mp.getCount();
for (int z = 0; z < partsCount; z++) {
System.out.println("Content Type: "+z+" "+mp.getBodyPart(z).getContentType());
if(mp.getBodyPart(z).getContentType().contains("text/plain"))
{answer = (String) mp.getBodyPart(z).getContent();}
}
}
}
}
}
return answer;}}
Related
I'm trying to do a batch request using MS Graph .NET SDK as shown here: https://learn.microsoft.com/en-us/graph/sdks/batch-requests?tabs=csharp
The only problem is that when I run the code, nothing happens.
I'm trying to move a set of emails (stored in a list) to another mail folder.
Am I missing anything?
The move request is here https://learn.microsoft.com/en-us/graph/api/message-move?view=graph-rest-1.0&tabs=http
When used in a single query it works, but not when batching.
Below you will find the code, in this case I'm looping to 20 just to test as 20 is the maximum queries per batch.
Thanks in advance.
for (int i = 0; i < 20; i++)
{
var mail = invalidMessages[i];
var userRequest = client.Me.Messages[mail.Id]
.Move(failureFolderID)
.Request();
requestID = batchRequestContent.AddBatchRequestStep(userRequest);
}
var returnedResponse = await client.Batch.Request().PostAsync(batchRequestContent);
EDIT: I tried to change the method to POST
userRequest.Method = System.Net.Http.HttpMethod.Post;
but I get a ServiceException: 'Code: BadRequest
Message: Write request id : fe23b1c1-663d-4499-829a-291d04a12b48 does not contain Content-Type header or body.'
The Microsoft Graph message-move API call you are attempting to use is a POST request
The Microsoft Batch API handles POST requests differently than the other API methods.
As per https://learn.microsoft.com/en-us/graph/sdks/batch-requests?tabs=csharp
POST requests are handled a bit differently.
The SDK request builders generate GET requests, so
you must get the HttpRequestMessage and convert to a POST
To have a successful post with the batch API you need to
Create an HttpRequestMessage
provide a value for the HttpRequestMessage's Content property which houses the POST requests payload
So if I applied this to your code I would first create a class to represent the POST payload for the message-move API. As per https://learn.microsoft.com/en-us/graph/api/message-move?view=graph-rest-1.0&tabs=http
the POST API has one property called destinationId
destinationId - The destination folder ID, or a well-known folder name. For a list of supported well-known folder names, see mailFolder resource type.
public class MailMovePayload
{
public string destinationId { get; set; }
}
then I would use an instance of this class in this modified version of you code
string str = events.Content.ReadAsStringAsync().Result;
events.Method = HttpMethod.Post;
for (int i = 0; i < 20; i++)
{
var mail = invalidMessages[i];
//get the request message object from your request
var userRequestMessage = client.Me.Messages[mail.Id]
.Move(failureFolderID)
.GetHttpRequestMessage();
//set the message API method
userRequestMessage.Method = HttpMethod.Post;
//create the payload, I am assuming failureFolderID is
//the name of the folder where the mail will be moved to
var payloadData = new MailMovePayload { destinationId = failureFolderID };
//make the JSON payload for the request message
userRequestMessage.Content = new StringContent(JsonConvert.SerializeObject(payloadData), Encoding.UTF8, "application/json")
requestID = batchRequestContent.AddBatchRequestStep(userRequestMessage);
}
var returnedResponse = await client.Batch.Request().PostAsync(batchRequestContent);
return httpRequestMessage;
}
i'm trying to generate swagger JSON files using https://github.com/pseudomuto/protoc-gen-doc, I can't find a way to exclude some of the APIs of the grpc service/fields inside the messages.
found the relevant styling in swagger, but can't seem to find a way to add it in the protobuf file http://watson-developer-cloud.github.io/api-guidelines/swagger-coding-style.html#excluding-operations-from-the-sdks
service MyService {
rpc ExternalApi (ExternalApiRequest) returns (ExternalApiResponse) {
option (google.api.http) = {
post: "/my/externalApi"
};
}
rpc InternalApi (InternalApiRequest) returns (InternalApiResponse) {
option (google.api.http) = {
post: "/my/internalApi"
};
}
message ExternalApiResponse {
string prefix = 1;
string id = 2; // field to exclude
}
// message to exclude
message Header { }
is there a way to exclude actions / fields from the protocol buffer files?
You can add
string id = 2 [(grpc.gateway.protoc_gen_swagger.options.openapiv2_field).read_only = true];
When we get email using Microsoft Graph/Outlook REST API it's body contains the references for embedded images like below.
<img src="cid:image001.jpg#1D3E60C.5A00BC30">
I am looking to find out a way so i can display the embedded images properly as the above image tag does not display any image. I have done some search but did not found any help on that.
Below is sample code for getting an email by id using Microsoft Graph API.
// Get the message.
Message message = await graphClient.Me.Messages[id].Request(requestOptions).WithUserAccount(ClaimsPrincipal.Current.ToGraphUserAccount()).GetAsync();
For getting attached resources with email using Microsoft Graph API you need to get email like below.
// Get the message with all attachments(Embedded or separately attached).
Message message = await graphClient.Me.Messages[id].Request(requestOptions).WithUserAccount(ClaimsPrincipal.Current.ToGraphUserAccount()).Expand("attachments").GetAsync();
Once you have all attachments with email detail you need to iterate through attachments list and check if attachment IsInline property is set as true then simply replace the
cid:image001.jpg#1D3E60C.5A00BC30
with Base64String created from bytes array of attachment.
string emailBody = message.Body.Content;
foreach (var attachment in message.Attachments)
{
if (attachment.IsInline.HasValue && attachment.IsInline.Value)
{
if ((attachment is FileAttachment) &&(attachment.ContentType.Contains("image")))
{
FileAttachment fileAttachment = attachment as FileAttachment;
byte[] contentBytes = fileAttachment.ContentBytes;
string imageContentIDToReplace = "cid:" + fileAttachment.ContentId;
emailBody = emailBody.Replace(imageContentIDToReplace,
String.Format("data:image;base64,{0}", Convert.ToBase64String(contentBytes as
byte[])));
}
}
}
Now render the email body using emailBody variable it will display all embedded images.
Use below code to display logo image on image tag using graph Api in C#.
var fileAttachment = new FileAttachment
{
ODataType = "#microsoft.graph.fileAttachment",
Name = Path.GetFileName(attachment),
ContentLocation = attachment,
ContentBytes = contentBytes,
ContentType = contentType,
ContentId= contentId,
IsInline = true
};
Note : Here IsInline = true must need to be added if you want to display image on image tag only not as attachment.
I am trying to do use the post method for a simple suitescript program, i am very new to this.
In Netsuite i have written a suitescript as follows.
function restPost()
{
var i = nlapiLoadRecord('department', 115);
var memo = nlapisetfieldvalue('custrecord225', ' ');// this is a customfield, which i want to populate the memo field, using rest client in firefox
var recordId = nlapiSubmitRecord(i);
}
i have created a script record and uploaded this suitescript and even copied the external URL to paste it in restclient.
In Restclient(firefox plugin), pasted the external URL, i have given the method as post, header authorization given, content-type: application/json, and in body i put in {"memo":"mynamehere"};
In this the error i get is
message": "missing ) after argument list
I even tried it by writting other suitescript programs the errors i get is as follows:
Unexpected token in object literal (null$lib#3) Empty JSON string
Invalid data format. You should return TEXT.
I am kinda new to the programming world, so any help would be really good.
I think you are trying to create a RESTlet for POST method. Following is the sample code for POST method -
function createRecord(datain)
{
var err = new Object();
// Validate if mandatory record type is set in the request
if (!datain.recordtype)
{
err.status = "failed";
err.message= "missing recordtype";
return err;
}
var record = nlapiCreateRecord(datain.recordtype);
for (var fieldname in datain)
{
if (datain.hasOwnProperty(fieldname))
{
if (fieldname != 'recordtype' && fieldname != 'id')
{
var value = datain[fieldname];
if (value && typeof value != 'object') // ignore other type of parameters
{
record.setFieldValue(fieldname, value);
}
}
}
}
var recordId = nlapiSubmitRecord(record);
nlapiLogExecution('DEBUG','id='+recordId);
var nlobj = nlapiLoadRecord(datain.recordtype,recordId);
return nlobj;
}
So after deploying this RESTlet you can call this POST method by passing following sample JSON payload -
{"recordtype":"customer","entityid":"John Doe","companyname":"ABCTools Inc","subsidiary":"1","email":"jdoe#email.com"}
For Authorization you have to pass request headers as follows -
var headers = {
"Authorization": "NLAuth nlauth_account=" + cred.account + ", nlauth_email=" + cred.email +
", nlauth_signature= " + cred.password + ", nlauth_role=" + cred.role,
"Content-Type": "application/json"};
I can understand your requirement and the answer posted by Parsun & NetSuite-Expert is good. You can follow that code. That is a generic code that can accept any master record without child records. For Example Customer Without Contact or Addressbook.
I would like to suggest a small change in the code and i have given it in my solution.
Changes Below
var isExistRec = isExistingRecord(objDataIn);
var record = (isExistRec) ? nlapiLoadRecord(objDataIn.recordtype, objDataIn.internalid, {
recordmode: 'dynamic'
}) : nlapiCreateRecord(objDataIn.recordtype);
//Check for Record is Existing in Netsuite or Not using a custom function
function isExistingRecord(objDataIn) {
if (objDataIn.internalid != null && objDataIn.internalid != '' && objDataIn.internalid.trim().length > 0)
return true;
else
return false;
}
So whenever you pass JSON data to the REStlet, keep in mind you have
to pass the internalid, recordtype as mandatory values.
Thanks
Frederick
I believe you will want to return something from your function. An empty object should do fine, or something like {success : true}.
Welcome to Netsuite Suitescripting #Vin :)
I strongly recommend to go through SuiteScript API Overview & SuiteScript API - Alphabetized Index in NS help Center, which is the only and most obvious place to learn the basics of Suitescripting.
nlapiLoadRecord(type, id, initializeValues)
Loads an existing record from the system and returns an nlobjRecord object containing all the field data for that record. You can then extract the desired information from the loaded record using the methods available on the returned record object. This API is a core API. It is available in both client and server contexts.
function restPost(dataIn) {
var record = nlapiLoadRecord('department', 115); // returns nlobjRecord
record.setFieldValue('custrecord225', dataIn.memo); // set the value in custom field
var recordId = nlapiSubmitRecord(record);
return recordId;
}
I'm currently developing a Firefox add-on(using https://addons.mozilla.org/en-US/developers/docs/sdk/1.0/ ) that consumes an API where the return data is in xml.
My problem is that I need to parse the returned data, and would like to do that using a xml object.
Since the request module only supports JSON and Text ( https://addons.mozilla.org/en-US/developers/docs/sdk/1.0/packages/addon-kit/docs/request.html#Response ) I need to convert the response.text to XML.
The code looks like this:
var Request = require('request').Request
.......
var req = Request({
url: https://to-the-api.com,
content: {
op: 'get-the-data-op',
password: "super-sec",
user: "username"
},
onComplete: function (response) {
dataAsText = response.text;
console.log("output: " + dataAsText);
}
});
req.post();
I have tried to user (new DOMParser).parseFromString(response.text, 'text/xml') but unfortunately it just fails with a error like ReferenceError: DOMParser is not defined
The question is if anyone of you guys have been able to create a Xml object inside a Firefox add-on, and if so, how?
Looks like the capability to parse response as xml was present, but has been removed. check out this bugzilla reference
Can't you use a normal XMLHttpRequest if you want to process the response as XML?
If DOMParser is unavailable you can try E4X:
var xml = new XML(response.text);
alert(xml.children().length());
You want to use the XMLHttpRequest object to handle your xhr request. Then when you get a response back access the responseXML object of the request variable. In the responseXML you'll have the documentElement and can use the querySelectorAll or querySelector to find elements you want. In each element you want just grab the textContent you need.
Here's an example to get you going (this looks for the 'xmls' element in the response):
var request = new require("xhr").XMLHttpRequest();
request.open('GET', 'https://to-the-api.com', true);
request.onreadystatechange = function (aEvt) {
if (request.readyState == 4) {
if(request.status == 200) {
var xmls = request.responseXML.documentElement.querySelectorAll("xmls");
for (var i = 0; i < xmls.length; i++) {
console.log("xml", i, xmls[i], xmls[i].textContent);
}
}
else {
console.log('Error', request.responseText);
}
}
};
request.send(null);