Fetch raw e-mail text with EWS (headers, body and encoded attachments) - exchangewebservices

Is there a way to fetch the raw email text using EWS?
I would like to get the whole text including headers, body, and encoded attachments.
Is this possible?

I don't know if this is what you are looking for, but it should help.
It downloads the entire message file, including encoded attachments, header, subject, sender, receiver, etc...
try this:
static void Main(string[] args)
{
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new NetworkCredential("USR", "PWD", "Domain");
service.AutodiscoverUrl("someone#example.com");
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue));
Console.WriteLine("Found : " + findResults.TotalCount + " messages");
foreach (EmailMessage message in findResults.Items)
{
try
{
message.Load(new PropertySet(ItemSchema.MimeContent));
MimeContent mc = message.MimeContent;
// I use this format to rename messages files, you can do whatever you want
string n = string.Format("-{0:yyyy-MM-dd_HH-mm-ss-ffff}.eml", DateTime.Now);
string path = #"C:\folder\message" + n;
FileStream fs = new FileStream(path, FileMode.Create);
fs.Write(mc.Content, 0, mc.Content.Length);
fs.Flush();
fs.Close();
//message.Delete(DeleteMode.HardDelete); // It deletes the messages permanently
//message.Delete(DeleteMode.MoveToDeletedItems); // It moves the processed messages to "Deleted Items" folder
}
catch (Exception exp)
{
Console.WriteLine("Error : " + exp);
}
}
}
catch (Exception exp2)
{
Console.WriteLine("Error : " + exp2);
}
}
Hope it helps, cheers.

Related

Javamail - CSVPrinter : send email with csv attached

I want to send an email with csv attachment without having to store the csv file on the server.
I create my csv :
StringWriter sw = new StringWriter();
try {
CSVPrinter csvPrinter = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(
"Année", "Mois", "Date", "Pièce", "Libellé",
"Débit", "Crédit", "Compte", "Journal"
));
for (ExportComptaAV export : exports){
csvPrinter.printRecord(export.getAnnee().getLibelle(),
export.getMois().getLibelle(),
export.getDateMouvement().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
export.getPiece(),
export.getLibelle(),
export.getMontantDebit().toString(),
export.getMontantCredit().toString(),
export.getNumCompte(),
export.getCodeJournal());
}
} catch (IOException e) {
e.printStackTrace();
}
And my email procedure :
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, CharEncoding.UTF_8);
InternetAddress ad = new InternetAddress("test#gmail.com");
message.addTo(ad);
message.setSubject(sujet);
message.setText(content, isHtml);
String fileName = "csvFile.csv";
message.addAttachment(fileName, new ByteArrayResource(...));
javaMailSender.send(mimeMessage);
} catch (MessagingException mex) {
throw mex;
}
So I would like to convert my CsvPrinter to a ByteArrayresource.
Is there a way to do that?
Get the String from the StringWriter, get the bytes from the String, and use them with ByteArrayResource.

Video Uploading Status in Vimeo

I am uploading video in Vimeo using my Application,But some of my videos status are not getting updated
I have followed the api document provided in this link: https://developer.vimeo.com/api/upload/videos:
I am using below code:
public boolean sendVideo(String file1, String completeURi, String endpoint, String id) throws FileNotFoundException, IOException {
File file = new File(file1);
long contentLength = file.length();
String contentLengthString = Long.toString(contentLength);
FileInputStream is = new FileInputStream(file);
int bufferSize = 20485760;
byte[] bytesPortion = new byte[bufferSize];
int byteNumber = 0;
while (is.read(bytesPortion, 0, bufferSize) != -1) {
String contentRange = Integer.toString(byteNumber);
boolean success = false;
int bytesOnServer = 0;
while (!success) {
long bytesLeft = contentLength - (bytesOnServer);
System.out.println(newline + newline + "Bytes Left: " + bytesLeft);
if (bytesLeft < bufferSize) {
//copy the bytesPortion array into a smaller array containing only the remaining bytes
bytesPortion = Arrays.copyOf(bytesPortion, (int) bytesLeft);
//This just makes it so it doesn't throw an IndexOutOfBounds exception on the next while iteration. It shouldn't get past another iteration
bufferSize = (int) bytesLeft;
}
bytesOnServer = sendVideoBytes("Vimeo Video upload", endpoint, contentLengthString, "video/mp4", contentRange, bytesPortion, first,isuploaded);
AppLog.e("bytesOnServer", "===contentLength===" + bytesOnServer +"&&=="+contentLengthString);
if (bytesOnServer >= Integer.parseInt(contentLengthString)) {
System.out.println("Success is true!");
return true;
} else {
contentRange = (bytesOnServer + 1) + "-" + (Integer.parseInt(contentLengthString)) + "/" + (Integer.parseInt(contentLengthString));
System.out.println(bytesOnServer + " != " + contentLength);
System.out.println("Success is not true!"+contentRange);
success=false;
first = true;
}
}
}
return true;
}
/**
* Sends the given bytes to the given endpoint
*
* #return the last byte on the server (from verifyUpload(endpoint))
*/
private static int sendVideoBytes(String videoTitle, String endpoint, String contentLength, String fileType, String contentRange, byte[] fileBytes, boolean addContentRange,boolean isuploaded) throws FileNotFoundException, IOException {
OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
request.addHeader("Content-Length", contentLength);
request.addHeader("Content-Type", fileType);
if (addContentRange) {
request.addHeader("Content-Range", "bytes " + contentRange);
}
request.addPayload(fileBytes);
Response response = signAndSendToVimeo(request, "sendVideo with file bytes " + videoTitle, false);
if (response.getCode() != 200 && !response.isSuccessful()) {
return -1;
}
return verifyUpload(endpoint, contentLength, contentRange,isuploaded);
}
/**
* Verifies the upload and returns whether it's successful
*
* #param
* #param contentLength
* #param endpoint to verify upload to #return the last byte on the server
*/
public static int verifyUpload(String endpoint, String contentLength, String contentRange,boolean isuploaded) {
// Verify the upload
OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
request.addHeader("Content-Length", "0");
request.addHeader("Content-Range", "bytes */*");
Response response = signAndSendToVimeo(request, "verifyUpload to " + endpoint, true);
AppLog.e("verifyUpload", "" + response.getCode());
if (response.getCode() != 308 || !response.isSuccessful()) {
return -1;
}
String range = response.getHeader("Range");
AppLog.e("After verify","==range header contains"+Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)));
//range = "bytes=0-10485759"
return Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)); //+1 remove
//return Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)) + 1;
//The + 1 at the end is because Vimeo gives you 0-whatever byte where 0 = the first byte
}
public static Response signAndSendToVimeo(OAuthRequest request, String description, boolean printBody) throws org.scribe.exceptions.OAuthException {
String newline = "\n";
System.out.println(newline + newline
+ "Signing " + description + " request:"
+ ((printBody && !request.getBodyContents().isEmpty()) ? newline + "\tBody Contents:" + request.getBodyContents() : "")
+ ((!request.getHeaders().isEmpty()) ? newline + "\tHeaders: " + request.getHeaders() : ""));
service.signRequest(OAuthConstants.EMPTY_TOKEN, request);
Response response = request.send();
// AppLog.e("Uplaod Video aftre Response", "" + response.getCode());
return response;
}
Can anyone help with a working code for Android??
Thanks in advance!!
I recently had the same problem with vimeo. The api returns the state VIMUploadState_Succeeded for the upload process, but if you try to watch the video at vimeo.com it is stucked in the uploading state and it shows a black screen in the app when you try to reproduce the video.
I got the following answers from their support team:
It looks like this specific video
didn't change from the uploaded state to a failure state.
Sorry but the videos provided in those links never finished uploading
and are lost. They will need to be re-uploaded.
In our platform there are several videos uploaded everyday and it seems to have no pattern to identify when this uploading problem will happen. If it is not a problem for you to re-upload the video, vimeo can be a good solution since its price is really good in comparison to other video platforms, otherwise you should look for another video storage/playback solution.
It is difficult to check up your code without proper debugging.
Here's the workaround for your code with a little more functions added
You can check the code here

Windows Phone send Bitmap using multipart/form-data

My request need to look like this:
Content-Type: multipart/form-data; boundary=---BOUNDARY
-----BOUNDARY
name="receipt_photo"; filename="image_filename.jpg"
Content-Type: image/jpeg
-----BOUNDARY
I am trying to send it using following code
public async static Task addPhotosToReceipt(BitmapImage image, int idReceipt)
{
User user = PhoneApplicationService.Current.State["user"] as User;
if (user.customer.token != null)
{
RestConnector rc = new RestConnector();
byte[] data;
try
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap(image);
System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, image.PixelWidth, image.PixelHeight, 0, 100);
data = ms.ToArray();
}
string response = await rc.postAsyncData("/api/v1/receipts/" + idReceipt + "/receipt_photos/?token=" + user.customer.token, data);
if (response.Contains("error"))
{
MessageBox.Show(response);
}
}
catch (Exception ex)
{
}
}
}
//in RestConnector class
public async Task<string> postAsyncData(string adress, byte[] file)
{
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent("---BOUNDARY"))
{
content.Add(new StringContent("-----BOUNDARY\nname=\"receipt_photo\"; filename=\"image_filename.jpg\"\nContent-Type: image/jpeg\n-----BOUNDARY"));
content.Add(new StreamContent(new MemoryStream(file)));
using (var message = await client.PostAsync(basicUrl + adress, content))
{
var input = await message.Content.ReadAsStringAsync();
return input;
}
}
}
}
In response I should get URL's to uploaded photos, but instead I got URL's to default photos. I think there is something with my request because on android it works fine.
Maybe I choosed wrong way to create byte from my bitmap?

WP8 - Scheduled Task Agent for push notifications

I'm trying to interface my app with push notifications and the backend developer choose Pusher as notifications provider.
.NET SDK is very messy, untidy and synchronous, which it does not work on WP8, so I rewrote its and it works fine now.
The question is: is a Scheduled Task required for fetch the push notifications and update the tile/toast? Or there are any best method?
I can't change push provider sadly.
You can simply send Tile and Toast push notifications to the phone and they will work even if your app is not running. You do not need background task for that.
Here is sample code that I use in a desktop application to send push notifications to a Windows Phone 8.0:
const String toastTemplate =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>{0}</wp:Text1>" +
"<wp:Text2>{1}</wp:Text2>" +
"<wp:Param>{2}</wp:Param>" +
"</wp:Toast>" +
"</wp:Notification>";
String message = String.Format(toastTemplate, "Test", "updated: " + DateTime.Now.ToString(), "/Pages/SyncPage.xaml");
Status = await PushNotifiactionsManager.SendNotification(cfg.PushNotificationUri, message, 2);
public static async Task<string> SendNotification(string pushNotificationUri, string message, short notificationClass)
{
String responseText;
if (message.Length > 3072)
{
responseText = String.Format("The message must be <= 3072 bytes: {0}", message);
}
else
{
HttpClient request = new HttpClient();
// Add message headers.
request.DefaultRequestHeaders.Add("X-MessageID", Guid.NewGuid().ToString());
request.DefaultRequestHeaders.Add("X-NotificationClass", notificationClass.ToString());
if (notificationClass == 1)
{
request.DefaultRequestHeaders.Add("X-WindowsPhone-Target", "token");
}
else if (notificationClass == 2)
{
request.DefaultRequestHeaders.Add("X-WindowsPhone-Target", "toast");
}
try
{
// Send the message, and wait for the response.
HttpResponseMessage response = await request.PostAsync(pushNotificationUri, new StringContent(message));
IEnumerable<string> values;
String connectionStatus = String.Empty;
if (response.Headers.TryGetValues("X-DeviceConnectionStatus", out values))
{
connectionStatus = values.First();
}
String subscriptionStatus = String.Empty;
if (response.Headers.TryGetValues("X-SubscriptionStatus", out values))
{
subscriptionStatus = values.First();
}
String notificationStatus = String.Empty;
if (response.Headers.TryGetValues("X-NotificationStatus", out values))
{
notificationStatus = values.First();
}
responseText = String.Format("{0}: {1}, {2}, {3}, {4}",
notificationClass == 1 ? "Tile" :
notificationClass == 2 ? "Toast" : "Raw",
response.StatusCode,
connectionStatus, subscriptionStatus, notificationStatus);
}
catch (WebException ex)
{
responseText = ex.Message;
}
}
return "Notification response: " + responseText;
}

how to get string parameter from request when using multipart/form-data? [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 7 years ago.
i make html page to upload image with text box which has description form it .
i have use multipart/form-data ; in the dopost at servlet i get file using
ServletFileUpload upload = new ServletFileUpload();
to get string parameter i used request.getparameter();
but it always give me NULL ???
HOw can i get it ??
html ::
<form name="filesForm" action="/upload" method="post" enctype="multipart/form-data">
File : <input type="file" name="file">
<textarea name = "description"
rows = "4" cols = "30">Enter comments here.</textarea>
<input type="submit" name="Submit" value="Upload File">
at servlet :
ServletFileUpload upload = new ServletFileUpload();
upload.setSizeMax(500000000);
FileItemIterator iterator = null;
try {
iterator = upload.getItemIterator(req);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // to handle contents or
// instances of request.
FileItemStream item = null;
try {
item = iterator.next();
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // get access each item on iterator.
java.io.InputStream in = item.openStream(); // allows to read the items contents.
Blob imageBlob = new Blob(IOUtils.toByteArray(in)); // store each item on Blob
// object after converting them to Bytes.
/*……….
Note: we are concerned on uploading images files. So the type of files is either (.jpg or gif)
……….
*/
PersistenceManager pm = PMF.get().getPersistenceManager();
String counter="1";
ServletOutputStream outt = resp.getOutputStream();
//match incoming request Content type and invoke appropriate method for handel request
Its because when you have form enctype="multipart/form-data". You can not get other form fields by using request.getParameter("paramnName");. It will always give you NULL.
You have to use FormItem's isFormField() to check if its regular field or file.
Example:
try {
ServletFileUpload upload = new ServletFileUpload();
response.setContentType("text/plain");
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Got a form field: " + item.getFieldName() + " " +item);
} else{
System.out.println("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName());
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
response.getOutputStream().write(buffer, 0, len);
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Adding onto the answer and addressing the question #Sayo Oladeji
To get the value of an input field you can use the following:
System.out.println("Got a form field: " + item.getFieldName() + " " + Streams.asString(stream));