Javamail - CSVPrinter : send email with csv attached - csv

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.

Related

How to format the response from the servlet, so the dojo does not return an exception

According to the dojo tutorial and several examples here, I am trying to send multiple multiple file help. The files to the servlet will arrive in the directory, but the dojo will return the exception
I use dojo 1.10 and javax.servlet.http.HttpServlet v3.0.1
PrintWriter out = response.getWriter();
try {
if (ServletFileUpload.isMultipartContent(request)) {
try {
#SuppressWarnings("unchecked")
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File("/tmp/eshop/" + File.separator + name));
}
}
out.print("[{uploadresult:'Upload is ok!'}]");
} catch (Exception ex) {
out.print("{uploadresult: 'File upload failed due to : '" + ex+"}");
}
} else {
out.print("{uploadresult:'Sorry this servlet only handles file upload request.'}");
}
out.close();
} catch (Exception e) {
logger.error(e);
}
Error thrown :
/dojo/v1.10/dojox/form/uploader/_HTML5.js:80 Error parsing server
result: SyntaxError: Unexpected token u in JSON at position 2
at JSON.parse ()
at Object.eval (/dojo/v1.10/dojox/form/uploader/_HTML5.js:76)
at XMLHttpRequest. (dojo.js: 15) (anonymous) # /dojo/v1.10/dojox/form/uploader/_HTML5.js:80
/dojo/v1.10/dojox/form/uploader/_HTML5.js:81 [{uploadresult: 'Upload
is ok!'}]
First of all , set the response to json format
add first the response.setContentType("application/json");
And you thing you've to format the json correctly by adding quotes to the key like :
response.setContentType("application/json");
PrintWriter out = response.getWriter();
try {
if (ServletFileUpload.isMultipartContent(request)) {
try {
#SuppressWarnings("unchecked")
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File("/tmp/eshop/" + File.separator + name));
}
}
out.print("[{'uploadresult':'Upload is ok!'}]");
} catch (Exception ex) {
out.print("{'uploadresult': 'File upload failed due to : '" + ex+"}");
}
} else {
out.print("{'uploadresult':'Sorry this servlet only handles file upload request.'}");
}
out.close();
} catch (Exception e) {
logger.error(e);
}

Headers also inserting into database while upload csv file data

Here headers are also inserting into database .here uploading the csv file with comma separated data
string Feedback = string.Empty;
string connString = ConfigurationManager.ConnectionStrings["DataBaseConnectionString"].ConnectionString;
using (MySqlConnection conn = new MySqlConnection(connString))
{
var copy = new MySqlBulkLoader(conn);
conn.Open();
try
{
copy.TableName = "BulkImportDetails";
copy.FileName = fileName;
copy.FieldTerminator = ",";
copy.LineTerminator = #"\n";
copy.Load();
Feedback = "Upload complete";
}
catch (Exception ex)
{
Feedback = ex.Message;
}
finally { conn.Close(); }
}
return Feedback;
Use the NumberOfLinesToSkip property to skip the first line, like so:
copy.NumberOfLinesToSkip = 1;
The use of this property is clearly shown in the documentation for MySQLBulkLoader. You must make a habit of reading the documentation to resolve your queries before you post a question here.

Http post call in windows phone 8

I'm new to windows phone 8 development.
Could you please help me how to send the xml data to the server through http post calls in windows phone 8?
Thanks
This is a sample code I used in my project. Modify according to your needs
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url to submit to");
req.Method = "POST";
//Add a Header something like this
//req.Headers["SOAPAction"] = "http://asp.net/ApplicationServices/v200/AuthenticationService/Login";
req.ContentType = "text/xml; charset=utf-8";
//req.UserAgent = "PHP-SOAP/5.2.6";
string xmlData = #"<?xml version=""1.0"" encoding=""UTF-8""?>Your xml data";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(xmlData);
req.Headers[HttpRequestHeader.ContentLength] = byteArray.Length.ToString();
req.BeginGetRequestStream(ar =>
{
using (var requestStream = req.EndGetRequestStream(ar))
{
// Write the body of your request here
requestStream.Write(byteArray, 0, xmlData.Length);
}
req.BeginGetResponse(a =>
{
try
{
var response = req.EndGetResponse(a);
var responseStream = response.GetResponseStream();
using (var streamRead = new StreamReader(responseStream))
{
// Parse the response message here
string responseString = streamRead.ReadToEnd();
//If response is also XML document, parse it like this
XDocument xdoc = XDocument.Parse(responseString);
string result = xdoc.Root.Value;
if (result == "true")
{
//Do something here
}
else
Dispatcher.BeginInvoke(() =>
{
//result failed
MessageBox.Show("Some error msg");
});
}
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
//if any unexpected exception occurs, show the exception message
MessageBox.Show(ex.Message);
});
}
}, null);
}, null);

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

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.

WP7 - post json data to Web Service

I want to know the best way to send a small json string/ data to a web service. I can use WebClient or httpwebrequest that's not the issue, but i am mainly concerned about how to convert the string into json format and post with the request.
As suggested , here i am using json.net , following is the code :
Uri url = new Uri("http://example.com");
//Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
//
JObject json =
new JObject(
new JProperty("customer", new JObject
(
new JProperty("phoneNumber", "07700555555"),
new JProperty("name", "John")
))
,
new JProperty("pickupAddress", new JObject
(
new JProperty("street", "1 Seagull Lane"),
new JProperty("city", "London"),
new JProperty("county", "London"),
new JProperty("postcode", "E000XX"),
new JProperty("country", "England"),
new JProperty("longitude", "10.18"),
new JProperty("latitude", "12.214")
))
,
new JProperty("destinationAddress", new JObject
(
new JProperty("county", "London"),
new JProperty("street", "1 Snow Lane"),
new JProperty("longitude", "1.79"),
new JProperty("latitude", "1.294"),
new JProperty("postcode", "E00XX"),
new JProperty("country", "England"),
new JProperty("city", "London")
))
,
new JProperty("pickupTime", "1311467121460"),
new JProperty("notes", "some notes"),
new JProperty("accountNumber", "account1"),
new JProperty("accountPassword", "account password")
);
//
// Create the post data
// Demo POST data
//byte[] byteArray = Encoding.UTF8.GetBytes(json.ToString());
//byte[] byteArray = Encoding.UTF8.GetBytes("1233456");
//
JsonSerializer serializer = new JsonSerializer();
serializer.NullValueHandling = NullValueHandling.Ignore;
using (StreamWriter sw = new StreamWriter(postStream))
using (JsonWriter writer = new JsonTextWriter(sw))
{
//serializer.Serialize(writer, JsonConvert.SerializeObject(json));
json.WriteTo(writer,null);
}
//
// Add the post data to the web request
//postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
MessageBox.Show(Response);
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
Now the code seems to be ok , json data is created ok , but response from server is showing : "the server response e = {"The remote server returned an error: NotFound."}"
I don't know what's going wrong , please help friends ! Some one told me that i have to add something in header of the request i.e. The header should show: booking = {...JSON...}
You could use the built in DataContractJsonSerializer Class.
Alternatively, you may get better performance with json.net.