how to send url in email without encoding - java

I am using Amazon Simple Email Service java API to send mail to receivers.
I am sending URL in mail body inside tag.
My use case demands the user to double click on the URL received to prompt some action. (like confirmation mail)
Problem is the url gets encoded while receiving. On double clicking it gives page not found (404) error.
Original URL : http://something.com/confirm/email=abc#hotmail.com&regKey=somekey&confirm=true
When i double click on this URL on mail, the link is opened in address bar as :
http://something.com/confirm/email=abc%40hotmail.com%26regKey=somekey%26confirm=true
I am using AmazonSimpleEmailServiceClient. Code is below :
SendEmailRequest request = new SendEmailRequest().withSource(sourceAddress);
String confirmationURL="http://something.com/confirm/email=abc#hotmail.com&regKey=somekey&confirm=true";
List<String> toAddresses = new ArrayList<String>();
toAddresses.add(toEmail);
Destination dest = new Destination().withToAddresses(toAddresses);
request.setDestination(dest);
Content subjContent = new Content().withData("Confirmation Request");
Message msg = new Message().withSubject(subjContent);
// Include a body in both text and HTML formats
Content textContent = new Content().withData("Dear please go to the following URL:"+
confirmationURL+"\n\n");
Content htmlContent = new Content().withData("<p>Dear please go to the following URL:</p>"+
"<p>"+confirmationURL+"</p>");
Body body = new Body().withHtml(htmlContent).withText(textContent);
msg.setBody(body);
request.setMessage(msg)
UPDATE
Just found, this problem is occurring only when recipient email is in hotmail.com. Why microsoft always have to do something differently ? Somebody help !

Use the class java.net.URLEncoder:
String confirmationURL = URLEncoder.encode( "http://something.com/confirm/email=abc#hotmail.com&regKey=somekey& confirm=true", "UTF-8");

Related

How to create com.microsoft.graph.models.Message with attachment?

I'm trying to send email with inline attachment using MS Graph. I know how to send email without attachment but when I'm trying to send message with attachment I don't know how can I add this attachment to the message.
Here is my code:
// recipients
Recipient recipient = new Recipient();
EmailAddress emailAddress = new EmailAddress();
emailAddress.address = "tom#mail.com";
recipient.emailAddress = emailAddress;
List<Recipient> recipients = List.of(recipient);
// body
ItemBody body = new ItemBody();
body.contentType = BodyType.HTML;
body.content = "<html><body>my image:<br><img src='cid:my_image_CID'></body></html>";
// inline image
Attachment attachment = new Attachment();
attachment.isInline = true;
attachment.contentType = ".png";
attachment.id = "my_image_CID";
//attachment.contentBytes - I DON'T SEE THIS FIELD...
// message
Message message = new Message();
message.subject = "my subject";
message.body = body;
message.toRecipients = recipients;
//message.attachments = ??? - how to create this object?
there are examples in the internet that I can set attachment.contentBytes but I don't see this attribute.
For the message I can set attachments object which is of type
AttachmentCollectionPage
but I don't know how can I create this object.
I'm using the following versions:
Microsoft Graph Java SDK » 5.42.0
Microsoft Graph Java Core SDK » 2.0.14
You need to use FileAttachment which extends Attachment and has property contentBytes.

Create email (outlook format) on web-service side (Java) and send to front end and download

I want to write a service through which I can create a email message with (to, cc, bcc, subject, body) specified. Then I need to return this email message to front end and download it in ".oft" format, in such a way that when I click on this downloaded file; file should open with all the fields (to, cc, bcc, subject, body) populated.
I am using Java as backend technology and angular5 as front-end.
I have tried using javax.mail utility to create the email message and return it as byte array. Something like:
Properties prop = System.getProperties();
Session session = Session.getDefaultInstance(prop, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("emailAddr#domain.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("emailAddr#domain.com"));
msg.setSentDate(new Date());
msg.setSubject("subject");
msg.setText("text of msg");
//return it from service API as
response.getOutputStream().write(msg.toString().getBytes());
On front end (component.ts file) I am retrieving the response as :
//function gets called on button click
createEmailTemplate():void{
this.httpService.getEmail('serviceUrl')
.subscribe(
email => {
let filename = "SampleMailFile.oft";
let linkElement = document.createElement('a');
let blob = new Blob([email], { type: "message/rfc822"});
let url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", filename);
let clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
}
);
}
A MSG file is supposed to have the same format as an OFT file. If that’s true then you should be able to use jotlmsg to generate the file. You shouldn’t need to use JavaMail at all for this, since it’s intended to actually send the mail.
NOTE: I’ve not used this library before, so I can’t speak to whether this will truly work.

CarbonCopy to a gmail address doesn't seem to work

I'm using a DocuSign Java SDK and need the functionality of CarbonCopy as I need to send every document to a person within our company other than a Signer.
So when I use the gmail address for the Signer the email is sent. But when I use the gmail address for the CarbonCopy recipient the email is never sent and I do not get an error. The envelope id is returned as if everything went fine.
Is there anything that I'm missing? Is it possible to make that work?
// login call available off the AuthenticationApi
AuthenticationApi authApi = new AuthenticationApi();
// login has some optional parameters we can set
AuthenticationApi.LoginOptions loginOps = authApi.new LoginOptions();
loginOps.setApiPassword("true");
loginOps.setIncludeAccountIdGuid("true");
LoginInformation loginInfo = authApi.login(loginOps);
// note that a given user may be a member of multiple accounts
List<LoginAccount> loginAccounts = loginInfo.getLoginAccounts();
String accountId = loginAccounts.get(0).getAccountId();
Path path = Paths.get(sFilePath);
byte[] PDFContents = Files.readAllBytes(path);
// Create an envelope that will store the document(s), field(s), and recipient(s)
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please sign this document sent from Java SDK)");
// Add a document to the envelope
Document doc = new Document();
String base64Doc = DatatypeConverter.printBase64Binary(PDFContents);
doc.setDocumentBase64(base64Doc);
doc.setName("MaterialRequisition.pdf"); // can be different from actual file name
doc.setDocumentId("1");
List<Document> docs = new ArrayList<Document>();
docs.add(doc);
envDef.setDocuments(docs);
// add a recipient to sign the document, identified by name and email we used above
Signer signer = new Signer();
signer.setEmail(sApproverEmail);
signer.setName(sApproverName);
signer.setRecipientId("1");
CarbonCopy cc = new CarbonCopy();
cc.setEmail(sCCEmail);
cc.setName(sCCName);
cc.setRecipientId("2");
// create a signHere tab somewhere on the document for the signer to sign
// default unit of measurement is pixels, can be mms, cms, inches also
SignHere signHere = new SignHere();
signHere.setDocumentId("1");
signHere.setPageNumber("1");
signHere.setRecipientId("1");
signHere.setXPosition("100");
signHere.setYPosition("710");
// Can have multiple tabs, so need to add to envelope as a single element list
List<SignHere> signHereTabs = new ArrayList<SignHere>();
signHereTabs.add(signHere);
Tabs tabs = new Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
// add recipients (in this case a single signer) to the envelope
envDef.setRecipients(new Recipients());
envDef.getRecipients().setSigners(new ArrayList<Signer>());
envDef.getRecipients().getSigners().add(signer);
envDef.getRecipients().getCarbonCopies().add(cc);
// send the envelope by setting |status| to "sent". To save as a draft set to "created"
envDef.setStatus("sent");
// instantiate a new EnvelopesApi object
EnvelopesApi envelopesApi = new EnvelopesApi();
// call the createEnvelope() API to send the signature request!
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
logger.debug("Envelope Id "+ envelopeSummary.getEnvelopeId());
// Delete the PDF file that Logi generated
Files.delete(path);
CarbonCopy recipients will receive email only when the envelope gets completed by all the parties based on the recipient’s order. Have a look at the Carbon Copies Recipient description in this link.
Debug the code and make sure whether CarbonCopy values gets added inside the envDef.getRecipients().getCarbonCopies() before it hits the createEnvelope and when the full envelope process gets completed by the signer thereafter a copy will be sent to the carbon copy recipient mail address, to make sure of that sign into the CarbonCopy recipient email address an email must be received along with completed document where you can only view the document..

how to get file url from kaltura by entryid

I have to get video url uploaded on kaltura by entryId. I have seen kaltura api, but didn't get proper solution for that.I got something in php code:
$ks = $client->session->start($secret, $userId, KalturaSessionType::ADMIN, $partnerId, 86400, 'disableentitlement');
$client->setKs($ks);
$client->startMultiRequest();
$entryId = '1_u7aj9kasw'; //replace this with your entry Id
$client->flavorAsset->getwebplayablebyentryid($entryId);
$req1ResultFlavorId = '{1:result:0:id}'; //get the first flavor from the result of getwebplayablebyentryid
$client->flavorAsset->geturl($req1ResultFlavorId); //this action will return a valid download URL
$multiRequestResults = $client->doMultiRequest();
$downloadUrl = $multiRequestResults[1];
echo 'The entry download URL is: '.$downloadUrl;
but i have to do it with java ,what i have tried like :
KalturaConfiguration config = new KalturaConfiguration();
config.setEndpoint(envConfiguration.getKalturaUrl());
KalturaClient client = new KalturaClient(config);
String ks = client.generateSession(envConfiguration.getKalturaSecretKey(), "TestUploader",
KalturaSessionType.ADMIN, 101);
client.setKs(ks);
client.startMultiRequest();
String url = client.getFlavorAssetService().getUrl("entryid");
log.debug("url is::::::"+ url);
but i am getting url null .Please help.
Thanks in advance !!!

setting HTML text in MultiPartEmail

I have java code for sending email with attachment as below.
String myEmailId = "xx#yahoo.co.in";
String myPassword = "#xx";
String senderId = "yy#gmail.com";
try {
MultiPartEmail email = new MultiPartEmail();
email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator(myEmailId, myPassword));
email.setDebug(true);
email.setHostName("smtp.mail.yahoo.com");
email.addTo(senderId);
email.setFrom(myEmailId);
email.setSubject("The picture");
email.setMsg("<font face='verdana' size='3'>Here is the picture you wanted "
+ "<table>"
+ "<tr><th>id</th><th>Name</th></tr>"
+ "<tr><th>1</th><th>Name 1</th></tr>"
+ "<tr><th>2</th><th>Name 2</th></tr>"
+ "<tr><th>3</th><th>Name 3</th></tr>"
+ "<tr><th>4</th><th>Name 4</th></tr>"
+ "</table>"
+ "</font>");
// add the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("/Users/alkandari/Desktop/SMART/Fahim/test_small.pdf");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
attachment = new EmailAttachment();
attachment.setPath("/Users/alkandari/Desktop/SMART/Fahim/test.pdf");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
// send the email
email.send();
System.out.println("Mail sent!");
} catch (Exception e) {
System.out.println("Exception :: " + e);
}
All is working fine EXCEPT, the HTML code is displaying as it is.
In Email what I get is
<font face='verdana' size='3'>Here is the picture you wanted <table><tr><th>id</th><th>Name</th></tr><tr><th>1</th><th>Name 1</th></tr><tr><th>2</th><th>Name 2</th></tr><tr><th>3</th><th>Name 3</th></tr><tr><th>4</th><th>Name 4</th></tr></table></font>
Is there any parameter, email that I will receive will have proper HTML formatted data.
Note :
Actually I was using Email email = new SimpleEmail(); and doing above stuff where HTML part is working perfectly. However when I had to switch to attachment, I had to use MultiPartEmail email = new MultiPartEmail();.
I want to provide my answer here such that future me (and others) can see the complete code. For whatever reason, probably just me, I found these answers incomplete, or that they did not work for me. Like OP, I was trying to send an HTML based email with a PDF attachment. Here is what I ended up with using commons-email 1.4. Any comments will be appreciated.
Imports:
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.EmailAttachment;
Build your email object (obviously the actual details here should be yours)
MultiPartEmail email = new MultiPartEmail();
email.setHostName("smtp.yourhosthere.com");
email.setSmtpPort(25);
// authentication not always needed depending on your environment
email.setAuthenticator(new DefaultAuthenticator("username", "password"));
email.setTo("to#yourhosthere.com");
email.setFrom("from#yourhosthere.com");
Now your message details. Note that my HTML includes the HTML and BODY tags.
email.setSubject("Your subject here");
email.addPart("<div>Your html here</div>", "text/html; charset=UTF-8");
Now the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(filepath);
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
Now send the email
email.send();
I got answer.
Just changed MultiPartEmail email = new MultiPartEmail(); to MultiPartEmail email = new HtmlEmail();
You can't use email.setMsg()
But set message body as:
email.addPart( "<h1>MSG BODY</h1> <u>your</u> name", "text/html; charset=UTF-8" );

Categories

Resources