attach file from DAM to send mail in cq/AEM - aem

i was trying to send a mail from cq-DAM but failed.
i can send files from my own pc, i want to get the files from DAM
here is the code ::
#SuppressWarnings("unchecked")
final Enumeration<String> parameterNames = request.getParameterNames();
final Map<String, String> parameters = new HashMap<String, String>();
while (parameterNames.hasMoreElements()) {
final String key = parameterNames.nextElement();
parameters.put(key, request.getParameter(key));
}
Resource templateRsrc = request.getResourceResolver().getResource("/etc/notification/send-email.html");
String mailId = request.getParameter("mailId");
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("/media/intelligrape/MyFiles/Xtra/Crafting/Paper Work/images.jpg");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Picture of John");
attachment.setName("John");
int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
try {
final MailTemplate mailTemplate = MailTemplate.create(templateRsrc.getPath(), templateRsrc.getResourceResolver().adaptTo(Session.class));
final HtmlEmail email = mailTemplate.getEmail(StrLookup.mapLookup(parameters), HtmlEmail.class);
logger.error("PROPERTIES**************************** "+parameters);
email.addTo(mailId);
email.attach(attachment);
URL url = new URL("<any URL except localhost>");
String cid = email.embed(url, "Apache logo");
email.setHtmlMsg("<html><body>The ig logo - <img src=\"cid:"+cid+"\"></body></html>");
email.setTextMsg("Your email client does not support HTML messages");
messageGateway = messageGatewayService.getGateway(HtmlEmail.class);
messageGateway.send(email);
thanks in advance..:)

You can get InputStream of the DAM image and convert it to ByteArrayDataSource and then use attach(datasource,name,description) method to attach the DAM image to email.
Node contentNode = imageNode.getNode("jcr:content");
Binary imageBinary = contentNode.getProperty("jcr:data").getBinary();
InputStream imageStream = imageBinary.getStream();
ByteArrayDataSource imageDS = new ByteArrayDataSource(imageStream,"image/jpeg");
email.attach(imageDS,"Some Image","Some Description");

Related

How to send multiple email with attachments using send grid

I'm using the send grid api to send emails in my c# app, and I can't seem to figure out how to send an email with multiple attachments. I can send an email with a single attachement, but not multiple. I can see that there are four methods used for attachments(see below), but there is only one that allow you to send a list of attachements "IEnumerable attachments", however it's a return type is void. Can someone tell me how to send multiple attachments using the send gris api?
[![Send Grid methods for addding attachments](https://i.stack.imgur.com/Obf3n.png)](https://i.stack.imgur.com/Obf3n.png)
public async Task<SendResponse> SendHTMLWithAttachmentSendgrid(List<EmailAddress> recipientEmailList, string subject, string htmlContent, string[] attachmentFilePaths, bool showAllRecipients = false)
{
SendResponse emailResponse = new SendResponse();
try
{
List<SendGrid.Helpers.Mail.Attachment> attachments = new List<SendGrid.Helpers.Mail.Attachment>();
SendGrid.Helpers.Mail.Attachment attach = null;
//The total size of your email, including attachments, must be less than 30MB.
foreach (string item in attachmentFilePaths)
{
var stream = File.OpenRead(item);
//string[] contentArray = fileName.Split('.');
//string contentType = contentArray[1].ToString();
var streamCount = stream.ToString();
System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
byte[] bytes = br.ReadBytes((Int32)stream.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
string[] filePathArray = item.Split('\\');
string fileName = filePathArray.LastOrDefault();
attach = new SendGrid.Helpers.Mail.Attachment() { Filename = fileName, Content= base64String };
attachments.Add(attach);
}
var from = new EmailAddress(DefaultSenderEmailAddress);
var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, recipientEmailList, subject, string.Empty, htmlContent, showAllRecipients = false);
MailHelper.CreateSingleEmailToMultipleRecipients(from, recipientEmailList, subject, string.Empty, htmlContent, showAllRecipients = false).AddAttachments(attachments);
var response = await this.SendGridClient.SendEmailAsync(msg);
}
catch (Exception ex)
{
_logger.LogError($"The following error occurred:{ex.Message}.");
}
return emailResponse;
}
I'm expecting to send multiple attachments in my email, using the Send Grid Api

Hi All, I am struggling in rest API where i need to post an XML in body with header and get the response, can anyone post an example of how to do it?

String reqURL = baseUrl + data_oauth.get(PropLoad.getTestXmlData("URL"));
Template template = new Template();
String updatedUrl = template.getUpdatedURL(reqURL);
Map<String, String> headers = Template.getRequestData(data_oauth,PropLoad.getTestXmlData("HEADER"));
headers.entrySet().toString();
String updatedAuthor = template.getAuthorizationHeader(headers, methodDesc);
headers.put("Authorization", updatedAuthor);
String xmlRequest = Template.generateStringFromResource(data_oauth,"xmlbody");
Response response = webCredentials_rest.postCallWithHeaderAndBodyParamForXml(headers, xmlRequest, updatedUrl);
// am getting Unmarshalled as in response, can any help me on posting an POST request with XML body in it
You can send it like this:
URL url = new URL(urlString);
URLConnection connenction = url.openConnection();
OutputStream output = connenction.getOutputStream();
InputStream input = new FileInputStream(xmlFile);
byte[] buffer = new byte[4096];
int len;
while ((len = input .read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
input .close();
output.close();
And read the response like this:
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connenction.getInputStream()));
String readLine = reader.readLine();
while (readLine != null) {
stringBuilder.append(readLine);
readLine = br.readLine();
}

How to add image file in Adobe AEM JCR using rest API from .Net

I googled alot but not getting any documentation of Adobe AEM for restfull API. I tried the .Net code from
https://helpx.adobe.com/experience-manager/using/using-net-client-application.html.
But it creates folder instead of uploading content.
What are the parameters we need to pass to upload any image, mp4, pdf etc. Below is my c# code.
protected void Button1_Click(object sender, EventArgs e)
{
string fileName=FileUpload1.FileName;
String postURL = "http://localhost:4502/content/dam/geometrixx/" + fileName;
System.Uri uri = new System.Uri(postURL);
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(uri);
NetworkCredential nc = new NetworkCredential("admin", "admin");
httpWReq.Method = "POST";
httpWReq.Credentials = nc;
httpWReq.ContentType = "application/x-www-form-urlencoded";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = FileUpload1.FileBytes;
httpWReq.ContentLength = data.Length;
using (System.IO.Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseText = string.Empty;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
responseText = reader.ReadToEnd();
}
TextBox1.Text = responseText;
}
I'm not familar with .Net, but the question is more about how to create an asset in AEM. You didn't specify any version, so I tested my code only on AEM 5.6.1, but it should work also on AEM 6.X. In the following snippet you can see how you can upload new file using curl into a folder of your choice in dam, so you have only to make the call from your .Net code:
curl -u admin:admin -X POST -F file=#"/absolute/path/to/your/file.ext" http://localhost:4502/content/dam/the/path/you/wish/to/upload/myfolder.createasset.html
You are sending a POST request to the dam path where the file have to be uploaded with the selector "createasset" and the extension "html".
.net code for uploading files on Aem. Try below code.
var filelocation = AppDomain.CurrentDomain.BaseDirectory + "Images\\YourFile with Extension";
FileStream stream = File.OpenRead(filelocation);
byte[] fileBytes = new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
stream.Close();
var httpClientHandler = new HttpClientHandler()
{
Credentials = new NetworkCredential("admin", "Your Password"),
};
//var httpClient = new HttpClient(httpClientHandler);
using (var httpClient = new HttpClient(httpClientHandler))
{
var requestContent = new MultipartFormDataContent();
var imageContent = new ByteArrayContent(fileBytes);
requestContent.Add(imageContent, "file", "file nmae with extension");
var response1 = httpClient.PostAsync("http://siteDomain/content/dam/yourfolder.createasset.html", requestContent);
var result = response1.Result.Content.ReadAsStringAsync();
}

How to add new header to jersey client to upload multipart file

Please find below jersey client code to upload multipart file:
String url = "http://localhost:7070"
Client client = Client.create();
WebResource webresource = client.resource(url);
File file = new File("C://Data//image1.jpg");
File thumbnail = new File("C://Data/image2.jpg");
InputStream isthumbnail = new FileInputStream(thumbnail);
InputStream isfile = new FileInputStream(file);
FormDataMultiPart multiPart = new FormDataMultiPart();
FormDataBodyPart bodyPart1 = new FormDataBodyPart(FormDataContentDisposition.name("Thumbnail").fileName("thumbnail").build(), isthumbnail, MediaType.APPLICATION_OCTET_STREAM_TYPE);
FormDataBodyPart bodyPart2 = new FormDataBodyPart(FormDataContentDisposition.name("File").fileName("file").build(), isfile, MediaType.APPLICATION_OCTET_STREAM_TYPE);
multiPart.bodyPart(bodyPart);
multiPart.bodyPart(bodyPart1);
//New Headers
String fileContentLength = "form-data; contentLength=\""+Long.toString(file.length())+ "\"";
String thumbnailContentLength = "form-data; contentLength=\""+Long.toString(file.length())+ "\"";
final ClientResponse clientResp = webresource.type(MediaType.MULTIPART_FORM_DATA_TYPE).accept(MediaType.APPLICATION_XML).post(ClientResponse.class, multiPart);
System.out.println("File Upload Success with Response"+clientResp.getStatus());
I need to add the String fileContentLength and thumbnailContentLength as header
Content-Length.
How do i add the headers as part of multipart and post the request?Any help would be appreciated
Use a FormDataContentDisposition as an argument to FormDataBodyPart(FormDataContentDisposition formDataContentDisposition, Object entity, MediaType mediaType).
final FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
final String value = "Hello World";
final FormDataContentDisposition dispo = FormDataContentDisposition
.name("file")
.fileName("test.txt")
.size(value.getBytes().length)
.build();
final FormDataBodyPart bodyPart = new FormDataBodyPart(dispo, value);
formDataMultiPart.bodyPart(bodyPart);

Upload local file to SharePoint Online using HttpWebRequest

I'm trying to upload a file to a SharePoint online site that I have permissions for, I have tried using an HttpWebRequest to get an XDocument to allow me to upload a file but when I call an HttpWebResponse I get the error "The underlying connection was closed: An unexpected error occurred on a receive."
I'm unable to use SharePoint client object model as this app is to be used on PCs that don't have a SharePoint installation.
You will need to create a digest:
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
string cmd = "_api/contextinfo";
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
client.DefaultRequestHeaders.Add("ContentLength", "0");
StringContent httpContent = new StringContent("");
var response = client.PostAsync(cmd, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
JsonObject val = JsonValue.Parse(content).GetObject();
JsonObject d = val.GetNamedObject("d");
JsonObject wi = d.GetNamedObject("GetContextWebInformation");
retVal = wi.GetNamedString("FormDigestValue");
}
Then you can use the following example to upload the file and retrieve its metadata from the http response:
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
client.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
client.DefaultRequestHeaders.Add("binaryStringRequestBody", "true");
IRandomAccessStream fileStream = await path.OpenAsync(FileAccessMode.Read);
var reader = new DataReader(fileStream.GetInputStreamAt(0));
await reader.LoadAsync((uint)fileStream.Size);
Byte[] content = new byte[fileStream.Size];
reader.ReadBytes(content);
ByteArrayContent file = new ByteArrayContent(content);
HttpResponseMessage response = await client.PostAsync(String.Concat("_api/web/lists/getByTitle('Project Photos')/RootFolder/Files/add(url='", filename, ".jpg',overwrite='true')?$expand=ListItemAllFields"), file);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
var info = response.Content.ReadAsStringAsync();
JsonObject d = JsonValue.Parse(info.Result).GetObject();
string id = d["d"].GetObject()["ListItemAllFields"].GetObject().GetNamedValue("ID").Stringify();
}