Creating an email in Java - java

I would like to "create" an email using Java.
Here's what I mean:
Based on information I already have, I would like to make an email message open in Microsoft Outlook with the fields To, CC, Subject, Message Body, and attachments already populated (all now stored as strings, the directories for attachments are stored as strings as well).
The message needs to open in Outlook for the user to verify the contents and give the opportunity for adding more CC, slight adjustments to subject and message body.
From what I gather, it seems that the "best" way of achieving this is first creating a file on disk that Outlook can read, which contains my message, then opening it with outlook using something similar to the code below.
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("OUTLOOK Directory + CMD switches for opening files");
Ideally, I would like to use a simple framework for simply creating such a file using the strings I already have for the different fields (or achieving the same thing through a a non-simple framework).
If there's no "good" way of achieving the above, I'd settle for a method of just attaching my attachment file to a given Outlook template (.oft) file.
(3. I'll resort to my current solution of simply having the template open in Outlook, the attachment in Explorer, and prompt the user to drag the file into Outlook.)
I've looked at HSMF in Apache POI (I'm Apache POI for other parts of my program), but it appears to be rather experimental at this point, and I've been unable to find much documentation for it.
Does anyone have any suggestions on where to look?

Use the Desktop API with the URI constructor that will quote legal characters. This example code will open your default mail client with the headers populated.
public static void main(String[] args) throws Exception {
URI msg = new URI("mailto", "you#foo.com&cc=team#bar.com&subject=How to create email in Java?body=Use JavaMail.", (String) null);
Desktop.getDesktop().mail(msg);
}
The only limitation is that there is an upper limit to the length of the URI that the O/S can handle. On windows, the 'start' command also understands the syntax which is explained in RFC 2368.

Related

Freemarker embed image on ftl

I am trying to embed an image on a Freemarker ftl template to send as an email, I've based on this question Feemarker writing images to html, I did the exact same thing as this question said, but the email is being generated like this
What may be causing this error, and how to fix it?
My template looks like this
<img alt="My image" src="${imgAsBase64}" />
The image is a Chart, and I get the Base64 String, which I called imageBase64Str, via a Primefaces JavaScript function that generates the Base64 of the chart image, I pass it to the the bean and pass the parameter to the template like this
String encoded = imageBase64Str.split(",")[1];
byte[] decoded = Base64.decodeBase64(encoded);
String imgDataAsBase64 = new String(decoded);
String imgAsBase64 = "data:image/png;base64," + imgDataAsBase64;
emailParams.put("imgAsBase64", imgAsBase64);
String encoded = imageBase64Str.split(",")[1]; is suspicious. Looks like you are changing the base 64 string generated in some different way. Is the image actually a png or it's in another format? I think that if you remove that split and just do emailParams.put("imgAsBase64", imageBase64Str); it may work.
However you need to consider that this solution won't work for many email clients. According to this link https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/ Base64 embedded images are not supported on a few major email clients, web and standalone, including Gmail and Outlook. Given that they are the most common email clients you don't want to deliver a solution that doesn't work on them or most of your users are gonna be unhappy.
IMO your best bet is to host the images in a server and use fully qualified URLs in your freemarker template.
An alternative is using the attachment and reference them in the html source as explained here: https://stackoverflow.com/a/36870709/2546299 but it require changes on the way the emails are sent (need to add the attachments) so it may not be suitable for your case.

Apache James Mail Server - Save attachments on filesystem

I'm using Apache James version 3.0-beta1 and I would like to know if there is a way to save separately the body of the e-mails from the attachments. Right now both of them are saved inside the DB, that leads to a noticeable increase in the table size due to the fact that all the attachments are saved inside the MAIL_BYTES column in the shape of a byte stream.
Is there a way to move outside the DB the attachments and leave inside the DB only the body of the emails? On the long run this default behaviour will make my DB collapse.
You may simply write a mailet to get the attachments of the mail and then save them to a specific folder in your filesystem. To be more specific, in mailet, get the MimeMessage from org.apache.mailet.Mail, then use it to check if there are any attachments by using getFileName() method. This method returns file names if Disposition and ContentType headers are not null . If the result is not null, then that means in than bodyPart you have a file attached.Then using getInputStream() you can save it to anywhere you want.

Capture generated output file path and name using CSSDK

We are in the process of converting over to using the XSLT compiler for page generation. I have a Xalan Java extention to exploit the CSSDK and capture some meta data we have stored in the Extended Attributes for output to the page. No problems in getting the EA's rendered to the output file.
The problem is that I don't know how to dynamically capture the file path and name of the output file.
So just as POC, I have the CSVPath hard coded to the output file in my Java extension. Here's a code sample:
CSSimpleFile sourceFile = (CSSimpleFile)client.getFile(new CSVPath("/some-path-to-the-output.jsp"));
Can someone point me in the CSSDK to where I could capture the output file?
I found the answer.
First, get or create your CSClient. You can use the examples provided in the cssdk/samples. I tweaked one so that I captured the CSClient in the method getClientForCurrentUser(). Watch out for SOAP vs Java connections. In development, I was using a SOAP connection and for the make_toolkit build, the Java connection was required for our purposes.
Check the following snippet. The request CSClient is captured in the static variable client.
CSSimpleFile sourceFile = (CSSimpleFile)client.getFile(new CSVPath(XSLTExtensionContext.getContext().getOutputDirectory().toString() + "/" + XSLTExtensionContext.getContext().getOutputFileName()));

Reading messages dynamically in Java1.6

I've multiple messages file (messages_en.properties, messages_ch.properties)
These files are having some static html text & need some dynamic input param such as username so that it'll say Dear {0}, thanks for subscription....
Now i need to substitute username there after reading those contents from appropriate file.
How can I do that in Java? Is there any framework sample code available?
See the I18N trail. Nutshell version from that tutorial, using newer API methods:
ResourceBundle messages = ResourceBundle.getBundle("MessageBundle", Locale.getDefault());
String output = MessageFormat.format(messages.getString("msg.key"), "Mike");
Depending on your actual usecase there may be some shortcuts (e.g., web frameworks often include direct support for localization via tag libraries, some libraries wrap up some busywork, etc.)
Check MessageFormat out:
String result = MessageFormat.format(
"Dear {0} , thanks for subscription....", username);
You can combine it with ResourceBundle getString method to read the message from your properties files through its key and output the formatted, dynamically filled message.

Set [Automatically wrap text] in Java mail

i have an account register function, after user inputted personal data, an confirm email will be sent to that customer with a generated link. The problem is that: because the link is too long, it is broken into two lines (The second line is from character 76) and the second line does not belong the the first line (User cannot click on the whole link). I think this problem may come from the word wrap or something like that
In Outlook Express, under menu->Tools->Options->Send->HTML setting, we can set number of characters that the email content should be wrapped in each line by changing the value. Is there any way to set this function using core Java Mail?
Thank you in advance.
Word wrapping is done by the viewer (i.e. Outlook Express) not when sending email. I would guess that you are sending plain text emails and relying on the viewers to try and identify that it contains links. Try sending HTML mail and using ''
No, JavaMail is a library allowing you to send/receive email through Java. It is not an application like Outlook/Outlook Express or Thunderbird for that matter.
That said, you can write code that does the formatting before it invokes JavaMail to send the email out.
First, you can't set a setting in java mail to change a client's formatting.
Second, while my solution might not be the best answer to the question. It should help with the problem you are having.
Before adding your link into the body of the mail make sure you;
Put the link on a new line. "\n" ;)
Make a little method using URL shortening API like bitlyj for bit.ly to shorten the URL. Add the shortened link and walla!
msg.setContent("This is an example of adding a shortened URL\n"
+ shortLink("http://www.longlink.com")
+ "\n", "text/plain");
public String shortLink(String link) {
Url url = as("Username", "APIKey").call(shorten(link));
return url.getShortUrl();
}
Using this approach you shouldn't have any issues with word wrap stuff.

Categories