I am trying to send a html page as mail using javamail.
my html page contains a link
<a href>click here</a>
when i am sending the mail the link is showing as a plain text.what should i do? here is the code i used
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("modified html page","text/html");
message.setHeader("Content-Type", "text/html; charset=UTF-8");
message.setText(html, "utf-8");
message.setContent(html, "text/html; charset=utf-8");
please give me a suggestion.
Danny rightly points out setText internally calls setContent so what you are doing here is entirely redundant.
Only this would be enough :-
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("modified html page","text/html");
message.setContent(html, "text/html; charset=utf-8");
Also setContent internally calls
removeHeader("Content-Type");
removeHeader("Content-Transfer-Encoding");
So there is no point calling message.setHeader("Content-Type", "text/html; charset=UTF-8"); as it would be removed anyway.
See this answer on more details on how to send HTML emails
Related
I need to get ZenDesk ticket attachment content like encoded format. ZenDesk API provided only the content url. By using that content url I can only able to get the redirect page of that file. But I need to automate a process that file as Base64 encoded format. Thanks in advance.
Note : I tried to migrate ZenDesk to Salesforce via Dell Boomi.
I found a resolution for my problem and I guess it's the same as yours.
In salesforce apex code I got the url response from zendesk and I used subtring method to get URL of attachment.
After that I used Pagereferece to open the URL, see below:
String exampleMyResponse= '<html><body>You are being <a href="https://xxx.zdusercontent.com/attachment/000001/sdlfkashdf98709udfah?token=eyJhbGciOiJkaX46SgYrFzTEpYqUIzpQeNnl5BMBNoRnUOsgQj389Ei7nNcGOcfGYaavlqLL2qaIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..U8oX8QnYBM1lZMb6rhQGRA.NC3Z9kHC9ZE6HhygIHHan6xWYvoPqziVx76CZ6vcNYHBuAjV-LmBclVJYumKWKXA_PDhXX27z977XKYrLJZSc85a6lJTEqd-V2mP7U6O6r0_6E9hO8CWaA1dyxYYWw8kUsgMFUaPr0wCupxm3NbDzT03ZwO6EBJj79x4UZdauiXfEUrSwdl1pPahlQE2VfFo8DprgX9GQHzRFm5lwMrhA3crogo8Ox';
**//You need to authorize your domain "https://xxx.zdusercontent.com"** in remote site
Pagereference pg = new Pagereference(exampleMyResponse.substringAfter('href="'));
**Blob b = pg.getContentAsPDF();**//Here you can use getContent() too for another type of file
//Example to save PDF
Attachment att = new Attachment(Name = 'stvm_4', Body = b, ContentType = 'application/pdf', ParentId='Sobject_Id');
insert att;
I am trying to use DropBox API to get a thumbnail from DropBox and show them on Lightning Web Component in Salesforce, but can not do it because in a response Apex receiving body with black rhombs and question marks inside.
I use standard HTTP method to call
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer sl.validToken');
req.setHeader('Dropbox-API-Arg', '{"resource": {".tag": "path","path": "/folderName/pictureName.jpg"},"format": "jpeg","size": "w64h64","mode": "strict"}');
req.setHeader('Content-Type', 'text/plain; charset=utf-8');
req.setEndpoint('https://content.dropboxapi.com/2/files/get_thumbnail_v2');
req.setMethod('POST');
Http httpreq = new Http();
HttpResponse res = httpreq.send(req);
this is what I receive in body of response in Apex. The same response I have in Postman.
https://i.stack.imgur.com/90yjI.png
This is what I have in DropBox explorer with same values and headers (JSON)
https://i.stack.imgur.com/ytDxv.png
File scope is Read to everyone. SF Remote Site Settings & CSP Trusted Sites are set.
Short update:
I`ve been able to get JSON From header. I did use that piece of code:
List<String> headers = new List<String>(res.getHeaderKeys());
for(String key : headers){
System.debug('key ->>> '+key+' = '+res.getHeader(key));
}
String jsonString = res.getHeader('Dropbox-Api-Result');
System.debug('->>>ddd '+jsonString);
But still do not understand how to use it as a thumbnail in LWC.
Thank you in advance for your help.
The /2/files/get_thumbnail_v2 Dropbox API endpoint is a "content-download" style endpoint, meaning the "response body contains file content, so the result will appear as JSON in the Dropbox-API-Result response header". So, the illegible value you're receiving is the actual bytes of the thumbnail data itself. You're currently attempting to display it as text, but you'll instead need to save and display it as an image to see the thumbnail. Refer to your platform's documentation for information on how to display an image.
For reference, the Dropbox API v2 Explorer is built with knowledge of the different endpoint formats, so in this case it displays the metadata from the Dropbox-API-Result response header, and just offers the file data, in this case the thumbnail data, as a download via a "Download" button.
I am trying to get a file with the .rtf extension as an attachment with an email. I cannot seem to get it in my mailbox.
the code I currently use
try
{
Message msg = new MimeMessage(session);
msg.setFrom( ); // this is filled in but hidden for this question
msg.addRecipient();// this is filled in but hidden for this question
msg.setSubject("test email");
msg.setText("body test content");
msg.setSentDate(new Date());
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
FileDataSource source = new FileDataSource(receiveFile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.attachFile(backupFile);
messageBodyPart.setFileName("reportFile.rtf");
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Transport.send(msg);
}
receiveFile is the rtf file in question that needs to be send as an attachement.
Do not bother wtih server settings and such. I have send emails using this code so that works all just fine :). and had success sending .txt or .doc files as well so I know my info is correct. just when I try to send it as reportFile.rtf the mail just does not arrive. and I have tried 2 systems both together (the datahandler + source path and the attachFile path) and both did not really give me what I wanted.
Is a rtf file as attachment possible using javaMail or am I looking in the wrong direction?
After looking at it more closely with my co-worker we figured out that the email I used as sender was interperted as a spam and thus dumped it in the spam folder. now in itself this is not a problem since it was fine for testing. However it seems that if you keep spamming with that address the mail server indeed blocks like a good percentage of the mails i was sending. So this made it hard to debug since it sometimes got through and sometimes did not. the issues has been resolved now.
This is my code for attaching the files to the mail:
Multipart mp=new MimeMultipart("mixed");
BodyPart mbody=new MimeBodyPart();
mbody.setHeader("Content-Type", "text/html; charset=us-ascii");
mbody.setHeader("Content-Transfer-Encoding","7bit");
mbody.setContent(content2, "text/html");
mp.addBodyPart(mbody);
for(File file:f){
BodyPart mbody2=new MimeBodyPart();
DataSource ds=new FileDataSource(file.getAbsolutePath());
mbody2.setDataHandler(new DataHandler(ds));
mbody2.setFileName(ds.getName());
mbody2.setHeader("Content-Type", "multipart/mixed");
mbody2.setHeader("Content-Transfer-Encoding", "base64");
mp.addBodyPart(mbody2);
}
m.setContent(mp);
content2 is the html content I am embedding in the E-mail, and I am adding files from an arraylist f.
The problem here is that although the files get attached and I receive the E-mail fine, I am unable to open the attachments because the data is corrupt. This happens for all the files I've tried to attach like jpegs, pdfs, spreadsheets, word docs and txt files.
I read here: https://community.oracle.com/thread/1589120 that this could happen because JavaMail uses encoding that messes up the binary data of the file and adding mbody2.setHeader("Content-Transfer-Encoding", "base64"); should fix the problem but that doesn't work for me.
Any ideas on what could be wrong?
Thanks
Time for some debugging...
First, remove all of the setHeader calls; some of them are wrong and none of them should be necessary.
Next, determine if the problem is on the sending end or the receiving end. Try multiple mail readers to see if they all have problems with the attachments.
Try sending plain text attachments. Are they also corrupted?
Post the protocol trace showing what happens when you send a simple message with a simple attachment that fails, so we can see if the message is being constructed correctly.
What version of JavaMail are you using?
What mail reader are you using to view the attachments?
I am calling an API of FluidSurvey. when i make a POST request ... it post the request on the fluidSurvey but i didnt get the JSON response. rather it returns nothing. any suggestion??
my controller code
public class fluidSurvey{
public String tst{set;get;}
public String result{get;set;}
public PageReference chk() {
getData();
return null;
}
public void getData(){
String apiKey = 'xxxxxx';
String pwd = 'xxxxxx';
String u = 'https://app.fluidsurveys.com/api/v2/surveys/survey_id/responses/';
HttpRequest req = new HttpRequest();
Http http = new Http();
HTTPResponse res;
try{
req.setEndPoint(u);
req.setTimeout(2000);
req.setMethod('POST');
Blob headerValue = Blob.valueOf(apikey + ':' + pwd);
String authorizationHeader = 'Basic '+ EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);
req.setHeader('Content-Type', 'application/json');
req.setHeader('Content-Length','31999');
res = http.send(req);
tst= res.toString();
catch(Exception e){
System.debug('Callout error: '+ e);
System.debug(tst+'--------'+res);
}
}
}
and the Apex page code is
<apex:page controller="fluidSurvey">
<apex:form >
<apex:pageBlock title="New Fluid Surveys API">
<apex:outputText value="{!tst}"></apex:outputText><br/>
<apex:pageBlockButtons location="bottom">
<apex:commandButton value="Submit" action="{!chk}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
and api documentation link is http://docs.fluidsurveys.com/api/surveys.html#getting-a-list-of-surveys..
FluidSurveys Dev here.
Looks like you're doing a POST request, which according to the docs is for creating a new response. But your function is named getData, so I'm assuming you want to get a list of responses?
Change the request type from GET to POST and it should start to work.
Also, the response type will be application/json, but you shouldn't be setting the request type to that encoding.
If I'm mistaken and you're looking to submit a new response, then this code wouldnt work because you're not actually passing any content.
As you can see by http://docs.fluidsurveys.com/api/surveys.html#submitting-a-new-response you need to actually pass a dictionary of question ids and answers. The best way to figure out what the ids are or what the format is, is to first look at the response returned from a GET request.
The problem with my code was that i setting a content-length header, but not setting any body,the server is diligently waiting for the 3199 byte body. so after using the setBody method my code properly returns a json response
I wanted to add to this answer in that I found that some messages from Apex being posted to external endpoints were getting dropped by firewalls on the other end due to intrusion detection rules.
Apparently, there are conditions where on the Apex end, outbound messages do not conform to certain construction rules that prevent man-in-the-middle attacks and some firewalls or IDS are blocking them. This will appear on the Apex side as a "Read Time Out".
The specific IDS rule is CVE-2009-3555 (http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3555).
If you are experiencing read timeouts in Apex to external endpoints and can't isolate them to apex programming, you might do some logging on the destination firewall to see if this is the issue, and if it is, create an exception in that firewall for this type of case.