Unable to Convert Microsoft.Exchange.WebServices.Data.EmailMessage mail message to System.Net.Mail.MailMessage - exchangewebservices

Is there any way of converting Exchange EMailMessage to System.Net.Mail.MailMessage:
FindItemsResults<Item> result = exchange.FindItems(WellKnownFolderName.Inbox,subjectFilter, new ItemView(10));
I have tried iterating through the result, but do not know how to proceed with the conversion:
foreach(Item item in result)
{
EmailMessage message = EmailMessage.Bind(exchange, item.Id );
String body = message.Body.Text;
String mailSubject = message.Subject.ToString();
}

Not directly they are different types so you can't cast or covert them. You may want to consider accessing the MimeContent of the message https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-export-items-by-using-ews-in-exchange . This content can then be used parsed using MimeKit http://www.mimekit.net/docs/html/Parsing-Messages.htm#LoadMessage . MimeKit has the same type of functionality as System.Net.Mail.MailMessage if your just trying to resend a Message via SMTP.

You can transfer the attributes one by one like that
MailMessage mail = new MailMessage();
mail.From = new MailAddress(exchangeEmail.From.Address);
mail.Subject = exchangeEmail.Subject;
foreach(EmailAddress address in exchangeEmail.ToRecipients)
{
mail.To.Add(address.Address);
} ...
and put it in a function that takes a ews email message as a parameter.

Related

What is the efficient way to get the fields from this JSON object?

I've the following code that returns json object. And I need to filter sender email, subject, and creationDate. The code does the job but I felt like there is an efficient way to do it. I appreciate your suggestion.
ResponseEntity<String> response =
restTemplate.exchange(app.getResourceUrl() + personnelEmail+
MESSAGE+"/?$select=Sender,Subject,CreatedDateTime", HttpMethod.GET, request, String.class);
String str=response.getBody();
JSONObject jsonObject= new JSONObject(str);
JSONArray arrayList= (JSONArray)jsonObject.get("value");
List l=arrayList.toList();
for(int i=0;i<l.size();i++){
HashMap<String,HashMap> hashMap=(HashMap<String,HashMap>)l.get(i);
HashMap<String,HashMap> sender= hashMap.get("sender");
HashMap<String,String> senderEmail= sender.get("emailAddress");
String email= senderEmail.get("address");
}
Here is the json object I receive from MS Office API.
{"#odata.context":"https://graph.microsoft.com/v1.0/$metadata#users('user34.onmicrosoft.com')/messages(sender,subject,createdDateTime)","value":[{"#odata.etag":"W/\”sljkasfdiou7978klosadf\"","id”:"lkjasdfu97978KLJASDFS_WGHJJ76J897DKdcuvtymBTItq836K34PUAAAvoK3SAAA=","createdDateTime":"2016-08-27T04:07:08Z","subject":"View
your Office 365 Enterprise E3 billing
statement","sender":{"emailAddress":{"name":"Microsoft Online Services
Team","address”:"T45763#email.microsoftonline.com"}}},{"#odata.etag":"W/\”JUU70303\"","id”:”UEYO93988FK;O38GV3J884=","createdDateTime":"2016-08-26T15:28:47Z","subject":"Order
confirmation: Thank you for your
purchase","sender":{"emailAddress":{"name":"Microsoft Online Services
Team","address":"obue733#email.microsoftonline.com"}}},{"#odata.etag":"W/\”LJKOIU987983\"","id”:”ladjksflk83l.x8783LKFW3=","createdDateTime":"2016-06-24T03:03:26Z","subject":"Attention:
Your Microsoft Azure Active Directory Premium trial subscription will
be disabled soon","sender":{"emailAddress":{"name":"Microsoft Online
Services Team","address":"635cdeee#email.microsoftonline.com"}}}]}
By default Office 365 REST API response payload also includes common annotations such as:
odata.context: the context URL of the payload
odata.etag: the ETag of the entity, as appropriate
The below picture demonstrates it
As you've already might guessed it could be controlled via odata.metadata parameter:
The odata.metadata parameter can be applied to the Accept header of
an OData request to influence how much control information will be
included in the response.
Example (C# version)
The example demonstrates how to set odata.metadata=none format parameter via Accept header to indicate that the service SHOULD omit control information
using (var client = new HttpClient(handler))
{
var url = "https://outlook.office365.com/api/v1.0/me/messages?$select=Sender,Subject,DateTimeCreated";
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(GetMediaType("none",false,false)));
var result = await client.GetStringAsync(url);
var data = JObject.Parse(result);
foreach (var item in data["value"])
{
//process item;
}
}
where
private static string GetMediaType(string metadata,bool streaming,bool IEEE754Compatible)
{
return String.Format("application/json; OData.metadata={0}; OData.streaming={1}; IEEE754Compatible={2}",metadata,streaming, IEEE754Compatible);
}

Sending data from Dart to PHP using POST method

I am trying to send some data from Dart to PHP...
This is the code i am using to send the data from Dart:
button.onClick.listen((e) {
var req = new HttpRequest();
req.onReadyStateChange.listen((HttpRequestProgressEvent e) {
if (req.readyState == HttpRequest.DONE) {
print('Data submitted!');
}
});
req.open('POST', form.action);
req.send('hello from dart');
});
In my PHP file I am trying to use the string i have send from dart, but count($_POST) returns 0. $_POST seems to be empty...
Dart code DOES trigger the php script and 'Data submitted' is printed...
This is actually related to your PHP configuration. You can access the POST'd data with PHP's reserved variable: $HTTP_RAW_POST_DATA However the preferred method is to use php://input
I am very new to Dart, but you can use FormData in the send. So a quick and dirty way could be.
var data_form = new FormData(query('#My_form'));
button.onClick.listen((e){
var request = new HttpRequest():
request.open('POST', 'http://Localhost/form_data.php');
request.send(data_form);

How to deserialize the body of a brokered message in node js?

I am implementing socket.io server in node js (socketio.js) for my windows azure project. My worker role is in c#. And am sending a brokered message from worker role to socketio.js through service bus queue. But The object which am sending through the brokered message is not getting serialized into a json object. I dont know how to access the body of this brokered message in node js.
I can show how am sending the brokered message in the worker role and how am receiving it in the node js script.
The response body of brokered message(i.e message.body)
#rrayOfTestModelHhttp://schemas.datacontract.org/2004/07/Project.Model ☺i)http://www.w3.org/2001/XMLSchema-instance☺
TestModel is the name of the object model which am sending through the brokered message body.
Worker Role:
BrokeredMessage socketioMessage = new BrokeredMessage(messageObject);
WorkerRoleClient.Send(socketioMessage );
Node Js script:
serviceBusService.receiveQueueMessage(queue, function (error, receivedMessage) {
if (!error) {
console.log(receivedMessage);
if (receivedMessage != null) {
var messageBody = receivedMessage.body;
console.log(messageBody);
io.sockets.emit('news', messageBody);
}}
the message body i receive here is some plain unreadable string. And i am sending proper objects from the worker role. Please let me know if any of you have an idea about whats going wrong
Thanks
I finally found a way to de serialize it and getting the json objects.
Worker Role in C#
var recordsMessage = Newtonsoft.Json.JsonConvert.SerializeObject(data);
BrokeredMessage socketMessage = new BrokeredMessage(recordsMessage);
Receiving in Node js:
if (receivedMessage != null) {
var messageBody = receivedMessage.body;
var jsonString = messageBody.substring(messageBody.indexOf('['), messageBody.indexOf("]")+1);
var recordsQueue = JSON.parse(jsonString);
}
Hope this helps someone
I know it's an old ticket but i guess it might help people in the future as it helped me today :).
Instead of using substring from your nodejs app, you have the possibility to directly send the message in string without the automatic serialization.
To do so, use the following code :
using (Stream stream = new MemoryStream())
using (TextWriter writer = new StreamWriter(stream))
{
writer.Write("Start");
writer.Flush();
stream.Position = 0;
queueClient.Send(new BrokeredMessage(stream) { ContentType = "text/plain" });
}
Hope it will help,
Clément
I am also trying to find a reference to help doing this, please check the following link: http://www.rackspace.com/blog/node-swiz-node-js-library-for-serializing-deserializing-and-validating-objects-in-rest-apis/
it shows the serialization and the deserialization using Node JS in any of the requested format (JSON or XML)
let me know if this work with you :)

Am getting invalid XML as a response from EWS calls?

Am using EWS API to connect Exchange server. The connection was established, but I didn’t receive any response.
Am getting exception “The response received from the service didn't contain valid XML.”
The inner Exception was “DTD is prohibited in this XML document.”
I didn’t get what is DTD?
I was getting your problem until (after MUCH trial and error):
set TraceEnabled to true, this will dump the back and forth messages to console.
I used the URL https://yourexchangeserver/EWS/Exchange.asmx
e.g. my work uses BPOS, in asia pacific region, so : https://red003.mail.apac.microsoftonline.com/EWS/Exchange.asmx
Request a specific service version e.g. ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1)
Step 1 got me past your first problem - it was giving the Outlook Web Access html page.
Step 2 let me see that it was then requesting 2010_Sp1, but that version wasn't supported.
Step 3 got "Hello world" working/sending.
Another note if you use that server, I couldn't get it to take any version except 2007 SP1, and thus, no AutoDiscovery of the URL.
public static string sendMail_BPOS_EWS()
{
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.UseDefaultCredentials = false;
service.Credentials = new WebCredentials("some_address#server.com", "password");
service.Url = new Uri("https://red003.mail.apac.microsoftonline.com/EWS/Exchange.asmx");
Console.WriteLine(service.Url);
service.TraceEnabled = true;
EmailMessage mail = new EmailMessage(service);
mail.From = new EmailAddress("from_address#server.com");
mail.ToRecipients.Add("to_address#server.com");
mail.Subject = "Email Subject";
mail.Body = "Email Body";
mail.Send();
return "sent";
}
catch (Exception ex)
{
return ex.ToString();
}
}

Posting a File and Associated Data to a RESTful WebService preferably as JSON

In an application I am developing RESTful API and we want the client to send data as JSON. Part of this application requires the client to upload a file (usually an image) as well as information about the image.
I'm having a hard time tracking down how this happens in a single request. Is it possible to Base64 the file data into a JSON string? Am I going to need to perform 2 posts to the server? Should I not be using JSON for this?
As a side note, we're using Grails on the backend and these services are accessed by native mobile clients (iPhone, Android, etc), if any of that makes a difference.
I asked a similar question here:
How do I upload a file with metadata using a REST web service?
You basically have three choices:
Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
Send the file first in a multipart/form-data POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata.
Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.
You can send the file and data over in one request using the multipart/form-data content type:
In many applications, it is possible for a user to be presented with
a form. The user will fill out the form, including information that
is typed, generated by user input, or included from files that the
user has selected. When the form is filled out, the data from the
form is sent from the user to the receiving application.
The definition of MultiPart/Form-Data is derived from one of those
applications...
From http://www.faqs.org/rfcs/rfc2388.html:
"multipart/form-data" contains a series of parts. Each part is
expected to contain a content-disposition header [RFC 2183] where the
disposition type is "form-data", and where the disposition contains
an (additional) parameter of "name", where the value of that
parameter is the original field name in the form. For example, a part
might contain a header:
Content-Disposition: form-data; name="user"
with the value corresponding to the entry of the "user" field.
You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.
The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.
I know that this thread is quite old, however, I am missing here one option. If you have metadata (in any format) that you want to send along with the data to upload, you can make a single multipart/related request.
The Multipart/Related media type is intended for compound objects consisting of several inter-related body parts.
You can check RFC 2387 specification for more in-depth details.
Basically each part of such a request can have content with different type and all parts are somehow related (e.g. an image and it metadata). The parts are identified by a boundary string, and the final boundary string is followed by two hyphens.
Example:
POST /upload HTTP/1.1
Host: www.hostname.com
Content-Type: multipart/related; boundary=xyz
Content-Length: [actual-content-length]
--xyz
Content-Type: application/json; charset=UTF-8
{
"name": "Sample image",
"desc": "...",
...
}
--xyz
Content-Type: image/jpeg
[image data]
[image data]
[image data]
...
--foo_bar_baz--
Here is my approach API (i use example) - as you can see, you I don't use any file_id (uploaded file identifier to the server) in API:
Create photo object on server:
POST: /projects/{project_id}/photos
body: { name: "some_schema.jpg", comment: "blah"}
response: photo_id
Upload file (note that file is in singular form because it is only one per photo):
POST: /projects/{project_id}/photos/{photo_id}/file
body: file to upload
response: -
And then for instance:
Read photos list
GET: /projects/{project_id}/photos
response: [ photo, photo, photo, ... ] (array of objects)
Read some photo details
GET: /projects/{project_id}/photos/{photo_id}
response: { id: 666, name: 'some_schema.jpg', comment:'blah'} (photo object)
Read photo file
GET: /projects/{project_id}/photos/{photo_id}/file
response: file content
So the conclusion is that, first you create an object (photo) by POST, and then you send second request with the file (again POST). To not have problems with CACHE in this approach we assume that we can only delete old photos and add new - no update binary photo files (because new binary file is in fact... NEW photo). However if you need to be able to update binary files and cache them, then in point 4 return also fileId and change 5 to GET: /projects/{project_id}/photos/{photo_id}/files/{fileId}.
I know this question is old, but in the last days I had searched whole web to solution this same question. I have grails REST webservices and iPhone Client that send pictures, title and description.
I don't know if my approach is the best, but is so easy and simple.
I take a picture using the UIImagePickerController and send to server the NSData using the header tags of request to send the picture's data.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"myServerAddress"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:UIImageJPEGRepresentation(picture, 0.5)];
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"myPhotoTitle" forHTTPHeaderField:#"Photo-Title"];
[request setValue:#"myPhotoDescription" forHTTPHeaderField:#"Photo-Description"];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
At the server side, I receive the photo using the code:
InputStream is = request.inputStream
def receivedPhotoFile = (IOUtils.toByteArray(is))
def photo = new Photo()
photo.photoFile = receivedPhotoFile //photoFile is a transient attribute
photo.title = request.getHeader("Photo-Title")
photo.description = request.getHeader("Photo-Description")
photo.imageURL = "temp"
if (photo.save()) {
File saveLocation = grailsAttributes.getApplicationContext().getResource(File.separator + "images").getFile()
saveLocation.mkdirs()
File tempFile = File.createTempFile("photo", ".jpg", saveLocation)
photo.imageURL = saveLocation.getName() + "/" + tempFile.getName()
tempFile.append(photo.photoFile);
} else {
println("Error")
}
I don't know if I have problems in future, but now is working fine in production environment.
FormData Objects: Upload Files Using Ajax
XMLHttpRequest Level 2 adds support for the new FormData interface.
FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
function AjaxFileUpload() {
var file = document.getElementById("files");
//var file = fileInput;
var fd = new FormData();
fd.append("imageFileData", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", '/ws/fileUpload.do');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert('success');
}
else if (uploadResult == 'success')
alert('error');
};
xhr.send(fd);
}
https://developer.mozilla.org/en-US/docs/Web/API/FormData
Since the only missing example is the ANDROID example, I'll add it.
This technique uses a custom AsyncTask that should be declared inside your Activity class.
private class UploadFile extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// set a status bar or show a dialog to the user here
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// progress[0] is the current status (e.g. 10%)
// here you can update the user interface with the current status
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
private String uploadFile() {
String responseString = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/upload-file");
try {
AndroidMultiPartEntity ampEntity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
// this trigger the progressUpdate event
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File myFile = new File("/my/image/path/example.jpg");
ampEntity.addPart("fileFieldName", new FileBody(myFile));
totalSize = ampEntity.getContentLength();
httpPost.setEntity(ampEntity);
// Making server call
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = EntityUtils.toString(httpEntity);
} else {
responseString = "Error, http status: "
+ statusCode;
}
} catch (Exception e) {
responseString = e.getMessage();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
// if you want update the user interface with upload result
super.onPostExecute(result);
}
}
So, when you want to upload your file just call:
new UploadFile().execute();
I wanted send some strings to backend server. I didnt use json with multipart, I have used request params.
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFile(HttpServletRequest request,
HttpServletResponse response, #RequestParam("uuid") String uuid,
#RequestParam("type") DocType type,
#RequestParam("file") MultipartFile uploadfile)
Url would look like
http://localhost:8080/file/upload?uuid=46f073d0&type=PASSPORT
I am passing two params (uuid and type) along with file upload.
Hope this will help who don't have the complex json data to send.
You could try using https://square.github.io/okhttp/ library.
You can set the request body to multipart and then add the file and json objects separately like so:
MultipartBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("uploadFile", uploadFile.getName(), okhttp3.RequestBody.create(uploadFile, MediaType.parse("image/png")))
.addFormDataPart("file metadata", json)
.build();
Request request = new Request.Builder()
.url("https://uploadurl.com/uploadFile")
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
logger.info(response.body().string());
#RequestMapping(value = "/uploadImageJson", method = RequestMethod.POST)
public #ResponseBody Object jsongStrImage(#RequestParam(value="image") MultipartFile image, #RequestParam String jsonStr) {
-- use com.fasterxml.jackson.databind.ObjectMapper convert Json String to Object
}
Please ensure that you have following import. Ofcourse other standard imports
import org.springframework.core.io.FileSystemResource
void uploadzipFiles(String token) {
RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)
def zipFile = new File("testdata.zip")
def Id = "001G00000"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("id", id)
form.add('file',new FileSystemResource(zipFile))
def urld ='''http://URL''';
def resp = rest.post(urld) {
header('X-Auth-Token', clientSecret)
contentType "multipart/form-data"
body(form)
}
println "resp::"+resp
println "resp::"+resp.text
println "resp::"+resp.headers
println "resp::"+resp.body
println "resp::"+resp.status
}