I am using TinyMCE in my website to get some data
I am storing the data in the MySQL database .. I am storing the HTML generated from the RTE to the database
It works fine when I have to display the data on a browser and everything is neatly formatted
However When I try to send that via email ... I get HTML in the email (and that too escaped)
Emailer code (just a start) is as follows:
public static void sendMail(String to, String from, String subject, String content)
throws Exception
{
if(!ScribeBookConstants.isEmailEnabled())
return;
//String host = "s155.eatj.com";
String host = ScribeBookConstants.getEmailHost();
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
SMTPAuthenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(content);
Transport.send(msg);
}
I tried to send an email to a Gmail account ... and get escaped HTML in the message text
Unescape content before calling setText().
Actually found the solution
I just had to set the content type to "text/html"
Related
public static void sendEmail(String msgHeader, String msg, String emailId, String emailFrom) {
Properties props = new Properties();
props.put("mail.smtp.auth", "false");
props.put("mail.debug", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", mailServer);
props.put("mail.smtp.port", port#);
props.put("mail.smtp.auth.mechanisms", "NTLM");
props.put("mail.smtp.auth.ntlm.domain", domainName);
Session session = Session.getDefaultInstance(props, null);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(emailFrom));
to = emailId;
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(msgHeader);
message.setText(msg, "utf-8", "html");
message.saveChanges();
session.getDebug();
Transport.send(message);
// Copy message to "Sent Items" folder as read
Store store = session.getStore("ntlm");
store.connect(mailServer, emailFrom, pwd);
Folder folder = store.getFolder("Sent Items");
folder.open(Folder.READ_WRITE);
message.setFlag(Flag.SEEN, true);
folder.appendMessages(new Message[] {message});
store.close();
} catch (Exception ex) {
logger.error("Error occured while sending Email !", ex);
}
}
When I try to execute the code above, i am able to send out the emails. the issue is with saving the email. I get an error (NoSuchProviderException) at the line
Store store = session.getStore("ntlm");
I have a few questions on this:-
The email sending part works without password verification with ntlm. Is it possible to save the sent email into the sent items folder without password verification. If yes then how?
session.getStore doesnt work when i use
a. smtp - exception (Invalid provider)
b. ntlm - exception (NoSuchProviderException)
what should i use here.
Thanks in advance for your help.
"ntlm" is not a type of Store, it's an authentication mechanism. The store types supported by JavaMail are "imap" and "pop3". You almost certainly want "imap". Just like sending, you're going to need to supply your username and password when connecting to your imap server.
Also, upgrade to the current version of JavaMail if possible.
I currently have a program that sends users an email based on their information in my database. The email is built out in html and sends to the users email as a content type text/html. I want to try and see if I could somehow send this message to their phone using the email format ###########domain.com.
Obviously phones cant receive an HTML message, so I tried this:
-Removed the html and sent pure text, this did work, however for Verizon (the only service provider I tested) the text got cut off and the full message never sent. I only received the first part of the message.
Then I wondered if it was possible to somehow "screenshot" the html message and simply send the picture of the html display to the phone.
Here is my current code to send an email:
public static void email(String content, String address) {
final String username = "email";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
Address[] a = InternetAddress.parse("myemail");
message.setReplyTo(a);
message.setHeader("From: ", "Movie Alert");
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(address));
if (ShowFinder.showsFound > 1) message.setSubject("Movie Alert: " + ShowFinder.showsFound + " New Shows Found!");
else if (ShowFinder.showsFound == 1) message.setSubject("Movie Alert: " + ShowFinder.showsFound + " New Show Found!");
else message.setSubject("Unsubscribed");
StringBuilder sb = new StringBuilder();
sb.append(content);
message.setContent(sb.toString(), "text/html");
Transport.send(message);
System.out.println("Sent Email");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
So in conclusion I have the following questions:
-Is the reason the text got cut off because I am not sending the email properly, or because of the service provider?
-Is it possible to send a screenshot of the html display based on the html code through a text message?
Thanks!
I found a solution to send an html message to a phone! There is a jar called HTML2Image that will convert your html code into an image: https://code.google.com/p/java-html2image/
To make an image of the html you would do something like this:
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml("<b>Hello World!</b> Please goto <a title=\"Goto Google\" href=\"http://www.google.com\">Google</a>.");
imageGenerator.saveAsImage("hello-world.png");
Then you could send this new image like so:
Multipart mp = new MimeMultipart();
Message message = new MimeMessage(session);
MimeBodyPart mbp1 = new MimeBodyPart();
MimeBodyPart mbp2 = new MimeBodyPart();
message.setFrom(new InternetAddress("email"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toEmail));
mbp1.setText(text);
mp.addBodyPart(mbp1);
DataSource source = new FileDataSource(new File("screenshot location/hello-world.png"));
mbp2.setDataHandler(new DataHandler(source));
mbp2.setFileName("Screenshot.png");
mbp2.setHeader("Content-ID", "<image_cid>");
mp.addBodyPart(mbp2);
message.setContent(mp);
Transport.send(message);
I strongly suspect the text is getting cut off because of the service provider. There's probably a limit on the size of a single text message.
If you can't fit all the text you want into a short message, you might want to send a link to a web page containing all the information.
I am trying to send mail to my friends through my Java Mail application. I am able to do it successfully however the receiver's column in the mailbox shows the complete email address rather than the name of the sender. I tried changing various parameters but still the mailbox would show the full e-mail address rather than the name of the sender.
using this method to send the message:
public void send(String key){
String to=key;
String from="mygmailid";
String subject="wassp";
String text="Hello";
Properties props=new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.user", "myname");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session mailSession=Session.getDefaultInstance(props);
Message simpleMessage=new MimeMessage(mailSession);
InternetAddress fromAddress=null;
InternetAddress toAddress=null;
try{
fromAddress=new InternetAddress(from);
toAddress=new InternetAddress(to);
}
catch(AddressException e){
e.printStackTrace();
}
try{
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO,toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
transport.connect("smtp.gmail.com",465, "myid#gmail.com", "mygmailpassword");
transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
transport.close();
}
catch(MessagingException e){
e.printStackTrace();
}
}
I am calling this method as:
public static void main(String[] args) {
MailSender mailer=new MailSender();
mailer.send("friendmail#gmail.com");
}
You can set a name in the InternetAddress using
new InternetAddress("mail#example.com", "Your Name");
You should use the two string constructor of InternetAddress to pass in both the e-mail address and the person's name. The resulting e-mail will contain a string like Jarrod indicated.
InternetAddress fromAddress=new InternetAddress("my#example.com", "John Doe");
try {
String from = " EMAIL ID";
String SMTP_AUTH_PWD = " PASSWORD ";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.auth", "true");
String SMTP_HOST_NAME = "smtp.gmail.com";
int SMTP_HOST_PORT = 465;
javax.mail.Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
Transport transport = ((javax.mail.Session) mailSession)
.getTransport();
javax.mail.Message message = new MimeMessage(mailSession);
message.setSubject("Testing SMTP-SSL");
message.setContent("", "text/plain");
message.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(receiver));
transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, from,
SMTP_AUTH_PWD);
message.setFrom(new InternetAddress(from," YOUR PREFERED NAME "));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
message.setContent(multipart);
transport.sendMessage(message,
message.getRecipients(javax.mail.Message.RecipientType.TO));
}
How the from field is displayed is a client specific implementation detail.
Usually if the sender is in the form of "Sender Name" <sender#domain.com> the client will do the correct thing depending on configuration.
Some clients will infer the name information from their address book information if it is missing.
The answers above are correct but I found I needed to place in a try catch for it to work, here's what I found worked from sendemailwebapp demo application.
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(userName, "YourName"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
Try this code within the try block.You can initialize your name within the setFrom() method of MimeMessage.
simpleMessage.setFrom(new InternetAddress("Your mail id", "Your name"));
ie,
try{
simpleMessage.setFrom(new InternetAddress("Your mail id", "Your name"));
simpleMessage.setRecipient(RecipientType.TO,toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
transport.connect("smtp.gmail.com",465, "myid#gmail.com", "mygmailpassword");
transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
transport.close();
}
You can force to specify the sender's name by using the greater than and less than Symbol < > as per the following format:
String from="John Smith<friendmail#gmail.com>";
.
.
.
fromAddress=new InternetAddress(from);
or
public static void main(String[] args) {
MailSender mailer=new MailSender();
mailer.send("John Smith<friendmail#gmail.com>");
}
When receiving the email, the email recipient will see the name "John Smith" in his inbox. (Most email programs shows the name if specified. e.g. Outlook, gmail, hotmail, etc...)
I have an application that can send mails, implemented in Java. I want to put a HTML link inside de mail, but the link appears as normal letters, not as HTML link...
How can i do to inside the HTML link into a String? I need special characters? thank you so much
Update:
HI evereybody! thanks for oyu answers! Here is my code:
public static boolean sendMail(Properties props, String to, String from,
String password, String subject, String body)
{
try
{
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(body, "text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(mbp);
// Preparamos la sesion
Session session = Session.getDefaultInstance(props);
// Construimos el mensaje
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setContent(multipart);
message.addRecipient(
Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
// Lo enviamos.
Transport t = session.getTransport("smtp");
t.connect(from, password);
t.sendMessage(message, message.getAllRecipients());
// Cierre.
t.close();
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
And here the body String:
String link = "ACTIVAR CUENTA";
But in the received message the link appears as the link string, not as HTML hyperlink! I don't understand what happens...
Any solution?
Adding the link is as simple as adding the text inside the string. You should set your email to support html (it depends on the library you are using), and you should not escape your email content before sending it.
Update: since you are using java.mail, you should set the text this way:
message.setText(body, "UTF-8", "html");
html is the mime subtype (this will result in text/html). The default value that is used by the setText(string) method is plain
I'm just going to answer in case this didn't work for someone else.
I tried Bozho's method and for some reason the email wouldn't send when I did the setText on the message as a whole.
I tried
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(body, "text/html");
but this came as an attachment in Outlook instead of in the usual text. To fix this for me, and in Outlook, instead of doing the mbp.setContent and message.setText, I just did a single setText on the message body part. ie:
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(messageBody,"UTF-8", "html");
With my code for the message looking like this:
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
for(String str : to){
message.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
}
message.setSubject(subject);
// Create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(messageBody,"UTF-8","html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
Appending "http://" before the URL worked for me.
We can create html link in the email body by using java code.In my case I am developing reset password where I should create link and send to the user through the mail.you will create one string.With in a string you type all the url.If you add the http to the that .it behaves like link with in the mail.
Ex:String mailBody ="http://localhost:8080/Mail/verifytoken?token="+ token ;
you can send some value with url by adding query string.Her token has some encrypted value.
put mailBody in your mail body parameter.
ex": "Hi "+userdata.getFirstname()+
"\n\n You have requested for a new password from the X application. Please use the below Link to log in."+
"\n\n Click on Link: "+mailBody);
The above is the string that is parameter that you have to pass to your mail service.Email service takes parameters like from,to,subject,body.Here I have given body how it should be.you pass the from ,to,subject values according to your cast
you can do right way it is working for me.
public class SendEmail
{
public void getEmail(String to,String from, String userName,String password,Properties props,String subject,String messageBody)
{
MimeBodyPart mimeBodyPart=new MimeBodyPart();
mimeBodyPart.setContent(messageBody,"text/html");
MimeMultipart multipart=new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
Session session=Session.getInstance(props,new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(userName,password);
}
});
try{
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setContent(multipart);
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
message.setSubject("Have You got Mail!");
message.setText(messageBody,"UTF-8","html");
Transport.send(message);
}
catch(MessagingException ex){System.out.println(ex)}
public static void main(String arg[]){
SendEmail sendEmail=new SendEmail();
String to = "XXXXXXX#gmail.com";
String from = "XXXXXXXX#gmail.com";
final String username = "XXXXX#gmail.com";
final String password = "XXXX";
String subject="Html Template";
String body = "<i> Congratulations!</i><br>";
body += "<b>Your Email is working!</b><br>";
body += "<font color=red>Thank </font>";
String host = "smtp.gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
sendEmail.getEmail(to,from,username,password,props,subject,body);
}
}
Im developing a simple Email Application, I have done sending email using java with following code.`
public class SendMail {
public SendMail() throws MessagingException {
String host = "smtp.gmail.com";
String Password = "mnmnn";
String from = "xyz#gmail.com";
String toAddress = "abc#gmail.com";
String filename = "C:/Users/hp/Desktop/Write.txt";
// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtps.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("JavaMail Attachment");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
try {
Transport tr = session.getTransport("smtps");
tr.connect(host, from, Password);
tr.sendMessage(message, message.getAllRecipients());
System.out.println("Mail Sent Successfully");
tr.close();
} catch (SendFailedException sfe) {
System.out.println(sfe);
}
}
}`
I want to develope SMSAlert application using java. I want to get sms alerts to my number whenever i get mail. Is it possible in java. Thanks in advance.
An easy and free way to accomplish this is to send an email to your sms inbox.
Each provider has a different domain, but say for sprint emails sent to [mynumber]#messaging.sprintpcs.com will be texted to me.
There doesn't seem to be much of a delay, we have monitoring processes that send out emails and texts this way on error conditions and they arrive simultaneously.
Of course if your recipients are spread across multiple networks maintaining this sort of system gets trickier, because you've got to look up the email domains.
There have been quite a lot of posts about this already.
My advice is to go through a third party provider such as aspsms.com and then to use their API (web service or wathever).
This one has a .Net API, but with Java, you should be able to use the SOAP webservice.
See this answer
This discussion thread about Kannel and SMS Gateways might be of some help.