How to open Javamail attachment with JS - jakarta-mail

Im writing a simple email client for Gmail mail server and I'd like to be able to download attachments via web interface made with JS.
I donwloaded attachments into local folder
private List<File> getAttachmentsFromMessage (Message message, int j) throws IOException, MessagingException {
List<File> attachments = new ArrayList<>();
Multipart multipart = (Multipart) message.getContent();
for (int i = 0; i < multipart.getCount() ; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase( bodyPart.getDisposition())){
File file = new File("target\\att\\" + j +"_"+ bodyPart.getFileName());
((MimeBodyPart) bodyPart).saveFile(file);
attachments.add(file);
}
}
return attachments;
}
and then try to transfer them to web interface via links
for (let j = 0; j <links_to_attachments.length ; j++) {
attachment_holder = document.createElement('div');
let a = document.createElement('a');
a.setAttribute('href','http://localhost/javaProjects/CRM/target/att/1_att1.docx');
a.download = '1.docx';
a.appendChild(document.createTextNode('link'));
attachment_holder.appendChild(a);
}
But this method didnt work.
And also it seems there is no way to get direct link to attachment.
Could you please to help me with this problem? How could I get these attachments dowmloaded via links?

Related

Import large amounts of data from Excel file into SQL Server using .NET Core and Angular

I want to import data from Excel files into SQL Server. The size of the file is 22 MB and contains approximately 1 million rows, but I get the error timeout.
This is the code of my controller
[System.Web.Http.Route("UploadExcel")]
[System.Web.Http.HttpPost]
[RequestFormLimits(MultipartBodyLengthLimit = 409715200)]
[RequestSizeLimit(409715200)]
public string ExcelUpload()
{
string message = "";
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
using (AngularDBEntities objEntity = new AngularDBEntities())
{
if (httpRequest.Files.Count > 0)
{
HttpPostedFile file = httpRequest.Files[0];
Stream stream = file.InputStream;
IExcelDataReader reader = null;
if (file.FileName.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (file.FileName.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
else
{
message = "This file format is not supported";
}
DataSet excelRecords = reader.AsDataSet();
reader.Close();
var finalRecords = excelRecords.Tables[0];
for (int i = 0; i < finalRecords.Rows.Count; i++)
{
UserDetail objUser = new UserDetail();
objUser.UserName = finalRecords.Rows[i][0].ToString();
objUser.EmailId = finalRecords.Rows[i][1].ToString();
objUser.Gender = finalRecords.Rows[i][2].ToString();
objUser.Address = finalRecords.Rows[i][3].ToString();
objUser.MobileNo = finalRecords.Rows[i][4].ToString();
objUser.PinCode = finalRecords.Rows[i][5].ToString();
objEntity.UserDetails.Add(objUser);
}
int output = objEntity.SaveChanges();
if (output > 0)
{
message = "Excel file has been successfully uploaded";
}
else
{
message = "Excel file uploaded failed";
}
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
return message;
}
I added maxRequestLength="1048576" executionTimeout="999999" to the web.config file in the system.web section, and maxAllowedContentLength="1073741824" to security tag, but I am still facing this problem.
Knowing that when I upload small files, the data is added to the table
you can add all items in a list and finally use bulk insert. use can use Entity Framework Extensions.

Mule - Salesforce connector - Retrieve job failed results bulk v2 - not returning failed data

I am querying Salesforce Bulk api failed results in Mule. But it doesn't fetch the data. It jus shows the record id and error message. But if i check in workbench, it shows the id, error, datacolumns(a,b,c)
How to get those details..Is there any other way to get the bulk api v2 failed results in Mule
doing simple Transformation before logging
%dw 2.0
output application/json
---
payload
Debug Log :
On workbench, I get the actual data.
please share your thoughts why i don't see those data
#RestResource(urlMapping='/bulkapi/failures')
global without sharing class RestGetBulkAPIResults
{
#HttpGet
global static void getFailedRecords()
{
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
res.addHeader('Content-Type', 'application/json');
Http http = new Http();
HttpRequest httpReq = new HttpRequest();
HttpResponse httpRes = new HttpResponse();
httpReq.setMethod('GET');
httpReq.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
string path = '/services/data/v48.0/jobs/ingest/7502i000001fJG9AAM/failedResults/';
httpReq.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+ path);
httpRes = http.send(httpReq);
string op = httpRes.getBody();
string[] rowList = op.split('\n');
string[] headers = rowList[0].split(',');
integer columnsCount = headers.size();
integer dataRowsCount = rowList.size();
string fullFormattedData = '[';
for(integer rowIndex =1; rowIndex < dataRowsCount; rowIndex++)
{
string[] rowData = rowList[rowIndex].split(',');
string rowJsonData ='{';
for(integer columnIndex=0; columnIndex < columnsCount; columnIndex++)
{
rowJsonData += headers[columnIndex] + ':' + rowData[columnIndex] + ',';
}
rowJsonData = rowJsonData.removeEnd(',');
rowJsonData += '}';
fullFormattedData += rowJsonData;
}
fullFormattedData += ']';
system.debug('resp' + httpRes.getBody());
res.responseBody = Blob.valueOf(fullFormattedData);
res.statusCode = 200;
}
}

HTTP 204 error when sending File in response REST

This is my write to excel method which returns javax.ws.rs.core.Response
public Response writeToExcel(UserDeatilsVOWrapper listBook) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("Resource Information");
int rowCount = 0;
createHeaderRow(spreadsheet);
for (UserDetailsVO detailsVO : listBook.getUserDetailsList()) {
Row row = spreadsheet.createRow(++rowCount);
writeBook(detailsVO, row);
}
Response response = null;
try (FileOutputStream outputStream = new FileOutputStream(new File("ResourceInformation.xlsx"))) {
workbook.write(outputStream);
// header required to enable download pop-up and set file name
Response.ok().header("Content-Disposition", "attachment; filename=" + "ResourceInformation.xlsx").build();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
This is my web service:
#POST
#Path(WebServiceConstants.DOWNLOAD_EXCEL)
#Consumes(MediaType.APPLICATION_JSON)
public Response getFile(UserDeatilsVOWrapper wrapper) {
Response respose=new ExportToExcel().writeToExcel(wrapper);
return respose;}
I get a HTTP204 error. I'm using postman. I know, I'm doing a big mistake in write to excel method and when trying to send file along with response.
Also is there any possible way to write a file object on REST response without saving file on server? I'm doing terrible in here. any help is appreciated.
I do not see where you set your file to the response. Normally you would do something like this
File file = new File("ResourceInformation.xlsx"))
// Do your excel-writing here...
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition", "attachment; filename=" + "ResourceInformation.xlsx");
return response.build();

GMAIL API sending email with attachment in c#

I need help with sending email w/attachment using Gmail Api in c#.
I have read Google website on sending emails with attachment but the example is in java.
Its too late for the answer, but posting it in case anyone needs it:)
Need MimeKit library for this: can be installed from NuGet.
Code:
public void SendHTMLmessage()
{
//Create Message
MailMessage mail = new MailMessage();
mail.Subject = "Subject!";
mail.Body = "This is <b><i>body</i></b> of message";
mail.From = new MailAddress("fromemailaddress#gmail.com");
mail.IsBodyHtml = true;
string attImg = "C:\\Documents\\Images\\Tulips.jpg OR Any Path to attachment";
mail.Attachments.Add(new Attachment(attImg));
mail.To.Add(new MailAddress("toemailaddress.com.au"));
MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);
Message message = new Message();
message.Raw = Base64UrlEncode(mimeMessage.ToString());
//Gmail API credentials
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scope,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
//Send Email
var result = service.Users.Messages.Send(message, "me/OR UserId/EmailAddress").Execute();
}
Scope can be:
GmailSend or GmailModify
static string[] Scope = { GmailService.Scope.GmailSend };
static string[] Scope = { GmailService.Scope.GmailModify };
Base64UrlEncode function:
private string Base64UrlEncode(string input)
{
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(inputBytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
}
I have an example in VB.net. GMail API Emails Bouncing.
Google page provides examples in Java and Python only. The objects being used in the Java example are not available in .Net version of API. It is not possible to translate those examples.
Fortunately, it is quite easy to do the same in C#/VB. Just use plain old Net.Mail.MailMessage to create a message including attachments, then use MimeKit (NuGet it) to convert the message into string and pass the string (after encoding Base64) to "Raw" field of message.send of Gmail API.
There's nothing particular to sending an attachment with the Gmail API. Either way the Gmail API message.send() takes a full RFC822 email message in the message.raw field (urlsafe base64 encoded). The main trick is building up such an RFC822 email message string in your language. I imagine there are some MIME message librarys in C# and that's the main issue is finding those libraries. I don't do C# but javax.internet.mail.MimeMessage works well in java and the 'email' module is good for python.
This other post seems relevant:
How to send multi-part MIME messages in c#?
string[] Scopes = { GmailService.Scope.GmailSend };
string ApplicationName = "Gmail API App";
public GmailForm()
{
InitializeComponent();
SendHTMLmessage();
}
string Base64UrlEncode(string input)
{
var data = Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(data).Replace("+", "-").Replace("/", "_").Replace("=", "");
}
public void SendHTMLmessage()
{
//Create Message
MailMessage mail = new MailMessage();
mail.Subject = "Subject!";
mail.Body = "This is <b><i>body</i></b> of message";
mail.From = new MailAddress("youremail#gmail.com");
mail.IsBodyHtml = true;
string attImg = "C:\\attachment.pdf";
mail.Attachments.Add(new Attachment(attImg));
mail.To.Add(new MailAddress("receiver#mail.com"));
MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);
var msg = new Google.Apis.Gmail.v1.Data.Message();
msg.Raw = Base64UrlEncode(mimeMessage.ToString());
//Gmail API credentials
UserCredential credential;
using (var stream =new FileStream(Application.StartupPath + #"/credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,Scopes,"user",CancellationToken.None,new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
//Send Email
var result = service.Users.Messages.Send(msg, "me").Execute();
MessageBox.Show("Your email has been successfully sent !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Send emails with attachments in salesforce via sendgrid

I am trying to generate a pdf and attach to an email and send it.
I am using salesforce and sendgrid.
I am able to send emails but the problem is when I try to attach the pdf, the email is with the attachment, but this is broken, the file is not empty, but the pdf says is broken (I think is a problem of conversion)
here is the code
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
PageReference pdf = Page.include_attachment;
pdf.getParameters().put('id', 'xxxxxxxxxxxxxxxxxx');
blob fileBody = pdf.getContentAsPDF();
efa.setBody(fileBody);
efa.setFileName('test.pdf');
efa.setContentType('application/pdf;charset=UTF-8;');
send('xxxxx#xxxx.com','Test','Body Test', fileBody);
I tryied using
pdf.getContentAsPDF();
and
pdf.getContent();
but the result is the same.
Send method
public static void send(String emailRecipient, String emailSubject, String emailBody, Blob att){
Boolean success=true;
//construct the body of the request
String requestBody='';
requestBody += 'to='+EncodingUtil.urlEncode(emailRecipient,'UTF-8');
requestBody += '&from='+EncodingUtil.urlEncode(user.Email,'UTF-8');
requestBody += '&fromname='+EncodingUtil.urlEncode(user.Name,'UTF-8');
requestBody += '&subject='+EncodingUtil.urlEncode(emailSubject,'UTF-8');
requestBody += '&text='+EncodingUtil.urlEncode(emailBody.trim(),'UTF-8');
requestBody += '&html='+EncodingUtil.urlEncode(emailBody.trim(),'UTF-8');
requestBody += '&api_user=xxxxx';
requestBody += '&api_key=xxxxx';
requestBody += '&files[attachment.pdf]=#'+ EncodingUtil.base64Encode(att);
//construct request
HttpRequest req = new HttpRequest();
req.setEndpoint('https://sendgrid.com/api/mail.send.json');
req.setMethod('POST');
req.setBody(requestBody);
try{
//send request
Http h = new Http();
HttpResponse res = h.send(req);
//check response
String status = res.getStatus();
if(status.toUpperCase()=='OK'){
success=true;
}
else{
success=false;
}
}
catch(Exception e){
success=false;
}
}
Thank you
There is now a library/devtoolkit to do this for you. At the time of this writing it is in beta, but it is working. Disclaimer: I work at SendGrid and have just recently developed the library.
sendgrid-apex
You can rewrite your code to:
...
Blob att = pdf.getContentAsPDF();
public static void send(String emailRecipient, String emailSubject, String emailBody, Blob att){
SendGrid sendgrid = new SendGrid('username', 'password');
SendGrid.email email = new SendGrid.Email();
email.addTo(emailRecipient);
email.setFrom(user.Email);
email.setFromName(user.Name);
email.setSubject(emailSubject);
email.setText(emailBody.trim());
email.setHtml(emailBody.trim());
email.addAttachmentStream("attachment.pdf", att);
String response = sendgrid.send(email);
}

Resources