Set [Automatically wrap text] in Java mail - java

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.

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.

Creating an email in 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.

How do i send HTML email containing dynamic link via JAVA

I am trying to send a dynamic link via email with the following code.
Message messageSSL = new MimeMessage(session);
int hash=1000;
String content="click here";
messageSSL.setContent(content, "text/html");
However, i have failed to generate a dynamic link.The output in the mail is in the plain text format.
Output (In the mail):
click here
Even though, the following code works and generates a link called "click here".
String content="click here";
Thanks!!
I think the problem is with backward slash. We should be using forward slash in urls. Please change and try it.
The Apache Commons Email library has some useful classes that take care of the low-level details for stuff like making HTML email work properly. Check it out:
http://commons.apache.org/proper/commons-email/
can you please enclose the link by html tag and try once.
String content="<html><body>click here </body></html>";
i am using same library and working fine for me.
please check below thread
How Can I put a HTML link Inside an email body?

struts email application .Dynamic Html content for the email body

In a struts2 application I want email notification is to be sent when ever a user is logged in .
I want the mail body to be Html content, with the data entered by the User in run time.
Can any one suggest suggest the best way to do it !
Foe now iam using mail.jar and iam able to send the static content easily.
But facing difficulty
1. maintaining the long HTMl code string .
2. How to substitute the values in the string with the dynamic values
Please can somebody help me with a proper solution. Or Best practice to follow in Email application !
Thanks in Advance !
You can put the email body in a properties file and read it from there.
For substitution, you can define "placeholder" in your String like {FIRSTNAME} {LASTNAME} etc., and then do a replaceAll for the dynamic portions in your code.
What u need to look into is "freemarker". Its a library and u can achieve your purpose with it.
You can use an WYSIWYG (What You See Is What You Get) Editor like CKEditor or TinyMCE, letting the user writing the html without even knowing html.
Then, after the user submitted the body, you take the output that is pure html,
and inject it into the mail body.
End of story...
Just remember to set mimetype to text/html and not to text/plain , or you will see the tags instead of their representation...

How do I format a String in an email so Outlook will print the line breaks?

I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook.
I found a page on microsoft.com that says there's a 'Remove line breaks' "feature" in Outlook so does this mean there's no solution to get around that other than un-checking that setting?
Thanks
I've just been fighting with this today. Let's call the behavior of removing the extra line breaks "continuation." A little experimenting finds the following behavior:
Every message starts with continuation off.
Lines less than 40 characters long do not trigger continuation, but if continuation is on, they will have their line breaks removed.
Lines 40 characters or longer turn continuation on. It remains on until an event occurs to turn it off.
Lines that end with a period, question mark, exclamation point or colon turn continuation off. (Outlook assumes it's the end of a sentence?)
Lines that turn continuation off will start with a line break, but will turn continuation back on if they are longer than 40 characters.
Lines that start or end with a tab turn continuation off.
Lines that start with 2 or more spaces turn continuation off.
Lines that end with 3 or more spaces turn continuation off.
Please note that I tried all of this with Outlook 2007. YMMV.
So if possible, end all bullet items with a sentence-terminating punctuation mark, a tab, or even three spaces.
You can force a line break in outlook when attaching one (or two?) tab characters (\t) just before the line break (CRLF).
Example:
This is my heading in the mail\t\n
Just here Outlook is forced to begin a new line.
It seems to work on Outlook 2010. Please test if this works on other versions.
See also Outlook autocleaning my line breaks and screwing up my email format
You need to use \r\n as a solution.
Microsoft Outlook 2002 and above removes "extra line breaks" from text messages by default (kb308319). That is, Outlook seems to simply ignore line feed and/or carriage return sequences in text messages, running all of the lines together.
This can cause problems if you're trying to write code that will automatically generate an email message to be read by someone using Outlook.
For example, suppose you want to supply separate pieces of information each on separate lines for clarity, like this:
Transaction needs attention!
PostedDate: 1/30/2009
Amount: $12,222.06
TransID: 8gk288g229g2kg89
PostalCode: 91543
Your Outlook recipient will see the information all smashed together, as follows:
Transaction needs attention! PostedDate: 1/30/2009 Amount: $12,222.06 TransID: 8gk288g229g2kg89 ZipCode: 91543
There doesn't seem to be an easy solution. Alternatives are:
You can supply two sets of line breaks between each line. That does stop Outlook from combining the lines onto one line, but it then displays an extra blank line between each line (creating the opposite problem). By "supply two sets of line breaks" I mean you should use "\r\n\r\n" or "\r\r" or "\n\n" but not "\r\n" or "\n\r".
You can supply two spaces at the beginning of every line in the body of your email message. That avoids introducing an extra blank line between each line. But this works best if each line in your message is fairly short, because the user may be previewing the text in a very narrow Outlook window that wraps the end of each line around to the first position on the next line, where it won't line up with your two-space-indented lines. This strategy has been used for some newsletters.
You can give up on using a plain text format, and use an html format.
I had the same issue, and found a solution. Try this: %0D%0A to add a line break.
I have used html line break instead of "\n" . It worked fine.
Adding "\t\r\n" ( \t for TAB) instead of "\r\n" worked for me on Outlook 2010 . Note : adding 3 spaces at end of each line also do same thing but that looks like a programming hack!
You need to send HTML emails. With <br />s in the email, you will always have your line breaks.
The trick is to use the encodeURIComponent() functionality from js:
var formattedBody = "FirstLine \n Second Line \n Third Line";
var mailToLink = "mailto:x#y.com?body=" + encodeURIComponent(formattedBody);
RESULT:
FirstLine
SecondLine
ThirdLine
I had been struggling with all of the above solutions and nothing helped here, because I used a String variable (plain text from a JTextPane) in combination with "text/html" formatting in my e-mail library.
So, the solution to this problem is to use "text/plain", instead of "text/html" and no need to replace return characters at all:
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/plain");
For Outlook 2010 and later versions, use \t\n rather than using \r\n.
If you can add in a '.' (dot) character at the end of each line, this seems to prevent Outlook ruining text formatting.
Try \r\c instead of \n.
EDIT: I think #Robert Wilkinson had it right. \r\n. Memory just isn't what it used to be.
The \n largely works for us, but Outlook does sometimes take it upon itself to remove the line breaks as you say.
I also had this issue with plain/text mail type. Earlier, I used "\n\n" but there was two line breaks. Then, I used "\t\n" and it worked. I was using StringBuffer in java to append content.
The content got printed in next line in Outlook 2010 mail.
Put the text in <pre> Tags and outlook will format and display the text correctly.
i defined it in CSS inline in HTML Body like:
CSS:
pre {
font-family: Verdana, Geneva, sans-serif;
}
i defined the font-family to have to font set.
HTML:
<td width="70%"><pre>Entry Date/Time: 2013-09-19 17:06:25
Entered By: Chris
worklog mania
____________________________________________________________________________________________________
Entry Date/Time: 2013-09-19 17:05:42
Entered By: Chris
this is a new Worklog Entry</pre></td>
Because it is a query, only percent escaped characters work, means %0A gives you a line break. For example,
<a href="mailto:someone#gmail.com?Subject=TEST&amp;body=Hi there,%0A%0AHow are you?%0A%0AThanks">email to me</a>
I also had this issue with plain/text mail type.Form Feed \f worked for me.
Sometimes you have to enter \r\n twice to force outlook to do the break.
This will add one empty line but all the lines will have break.
\r\n will not work until you set body type as text.
message.setBody(MessageBody.getMessageBodyFromText(msg));
BodyType type = BodyType.Text;
message.getBody().setBodyType(type);
I was facing the same issue and here is the code that resolved it:
\t\n - for new line in Email service JavaMailSender
String mailMessage = JSONObject.toJSONString("Your message").replace(",", "\t\n").trim();
RESOLVED IN MY APPLICATION
In my application, I was trying to send an email whose message body was typed by the user in text area. When mail was send, outlook automatically removed line break entered by user.
e.g if user entered
Yadav
Mahesh
outlook displayed it as
YadavMahesh
Resolution: I changed the line break character "\r\n" with "\par " ( remember to hit space at the end of RTF code "\par" )and line breaks are restrored.
Cheers,
Mahesh
Try this:
message.setContent(new String(body.getBytes(), "iso-8859-1"),
"text/html; charset=\"iso-8859-1\"");
Regards,
Mohammad Rasool Javeed
I have a good solution that I tried it, it is just add the Char(13) at end of line like the following example:
Dim S As String
S = "Some Text" & Chr(13)
S = S + "Some Text" & Chr(13)
if the message is text/plain using, \r\n should work;
if the message type is text\html, use < p/>
if work need to be done with formatted text with out html encoding.
it can be easy achieved with following scenario that creates div element on the fly and using <pre></pre> html element to keep formatting.
var email_body = htmlEncode($("#Body").val());
function htmlEncode(value) {
return "<pre>" + $('<div/>').text(value).html() + "</pre>";
}
Not sure if it was mentioned above but Outlook has a checkbox setting called "Remove extra line breaks in plain text messages" and is checked by default. It is located in a different spot for different versions of Outlook but for 2010 go to the "File" tab. Select "Options => Mail" Scroll down to "Message format" Uncheck the checkbox.

Categories