Java : Java mail garbling the email-subject. - java

I am sending out an email pro-grammatically, but the subject in email is getting garbled(posted below). Can anyone tell me what I am doing wrong. Thanks a lot.
Code to send email :
final String from = "from#gmail.com";
final String emailPassword = "password";
final String to = "somemail#gmail.com";
final String ccMail = "ccmail#gmail.com";
String[] mailAddressTo = new String[2];
mailAddressTo[0] = to;
mailAddressTo[1] = ccMail;
InternetAddress[] mailAddress_TO = new InternetAddress[mailAddressTo.length];
for (int i = 0; i < mailAddressTo.length; i++)
{
try {
mailAddress_TO[i] = new InternetAddress(mailAddressTo[i]);
} catch (AddressException ignored) { }
}
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
from, emailPassword);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.addRecipients(Message.RecipientType.TO, mailAddress_TO);
message.setSubject("Es hat sich jemand für einen Kurs eingeschrieben");
String messageText = "some text";
message.setContent(messageText,"text/html;charset=UTF-8");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
Subject output :
=?ANSI_X3.4-1968?Q?Es_hat_sich_jemand_f=3Fr_einen_Kurs_eingeschrieben?=
The above output I am getting in mail-client and in browsers as well. What am I doing wrong?

This seems to be a problem with the used character set. To test this you could try to set the Character Encoding in your source code:
System.setProperty("mail.mime.charset","Cp1252");
I think the JavaMail API checks some properties but I can't remember wich ones.

Related

How to send java mail in spring mvc

I have an web application in which i am sending mail to user. Following is my code.
String host = "smtp.gmail.com";
String pwd = "123";
String from = "sender#gmail.com";
String to = "receiver#gmail.com";
String subject = "Test";
String messageText = "This is demo mail";
int port = 587;
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] add = {new InternetAddress(to)};
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setRecipients(Message.RecipientType.TO, add);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText); //Actual msg
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, from, pwd);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
This code is executed on local but fails on server domain. I have search a lot but that solution didn't work for me.
I tried a lot like replacing transport.connect(host, from, pwd); with transport.connect(host, 587, from, pwd); or 465and also String host="smtp.gmail.com"; with static domain IP. but still not working.
can anyone figure out what i am missing..?
Here is working example.
If this didn't work then there must be a problem with your server..
public static void sendEmail(String host, String port, final String userName, final String password, String recipient, String subject, String message, File attachFile) throws AddressException, MessagingException, UnsupportedEncodingException {
// sets SMTP server properties
try {
logger.info("Sending Email to : " + recipient + " Subject :" + subject);
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName, userName));
if (recipient.contains(";")) {
String[] recipientList = recipient.split(";");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String obj: recipientList) {
recipientAddress[counter] = new InternetAddress(obj.trim());
counter++;
}
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
} else {
InternetAddress[] recipientAddress = {
new InternetAddress(recipient)
};
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
}
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFile != null) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(attachFile);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
} catch (Exception e) {
logger.error("ERROR In Sending Email :" + e, e);
}
}

JavaMail API Error (javax.mail.NoSuchProviderException: invalid provider)

I'm trying to create a program using the JavaMail API, however, I keep getting the following error message.
javax.mail.NoSuchProviderException: invalid provider
at javax.mail.Session.getTransport(Session.java:738)
at javax.mail.Session.getTransport(Session.java:682)
at javax.mail.Session.getTransport(Session.java:662)
at EmailAutoResponder2.main(EmailAutoResponder2.java:56)
I was not able to solve it by reading online, as all of their solutions still gave me the same message.
Here is the Java code:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailAutoResponder2 {
public static void main(String[] args) {
String to = "username#videotron.ca";
String from = "username#videotron.ca";
Properties properties = System.getProperties();
properties.setProperty("mail.store.protocol", "imaps");
Session session1 = Session.getInstance(properties);
//If email received by specific user, send particular response.
Properties props = new Properties();
props.put("mail.imap.auth", "true");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.host", "imap.videotron.ca");
props.put("mail.imap.port", "143");
Session session2 = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username#videotron.ca", "password");
}
});
try {
Store store = session2.getStore("imap");
store.connect("imap.videotron.ca", "username#videotron.ca", "password");
Folder fldr = store.getFolder("Inbox");
fldr.open(Folder.READ_ONLY);
Message msgs[] = fldr.getMessages();
for(int i = 0; i < msgs.length; i++){
System.out.println(InternetAddress.toString(msgs[i].getFrom()));
if (InternetAddress.toString(msgs[i].getFrom()).startsWith("Name")){
MimeMessage message = new MimeMessage(session1);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject");
message.setText("Message");
String protocol = "imap";
props.put("mail." + protocol + ".auth", "true");
Transport t = session2.getTransport("imap");
try {
t.connect("username#videotron.ca", "password");
t.sendMessage(message, message.getAllRecipients());
}
finally {
t.close();
}
}
}
}
catch(MessagingException mex){
mex.printStackTrace();
}
catch(Exception exc) {
}
}
}
Thank you!
You're connecting to localhost to send the message. Do you have a mail server running on your local machine? Probably not. You need to set the mail.smtp.host property. You may also need to supply a username and password for your mail server; see the JavaMail FAQ.
The following code may solve your problem
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}

user is receiving same email twice in java

I am using the code below to send emails using java ,my project is running on a tomcat server.
the problem that user is receiving same email twice.
after some research it seems that java is sending email twice,any one can help me how I handle it?
Properties props;
Session session;
try {
props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "....");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.connectiontimeout", "2000");
props.put("mail.smtp.timeout", "2000");
props.setProperty("charset", "utf-8");
session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
// session.setDebug(true);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
if (!to.equals("") && to != null) {
String[] toArray = to.split(";");
InternetAddress[] toList = new InternetAddress[toArray.length];
for (int i = 0; i < toArray.length; i++) {
toList[i] = new InternetAddress(toArray[i]);
}
message.addRecipients(Message.RecipientType.TO, toList);
}
if (!cc.equals("") && cc != null) {
String[] ccArray = cc.split(";");
InternetAddress[] ccList = new InternetAddress[ccArray.length];
for (int i = 0; i < ccArray.length; i++) {
ccList[i] = new InternetAddress(ccArray[i]);
}
message.addRecipients(Message.RecipientType.CC, ccList);
}
message.setSubject(subject);
//message.setText(emailBody);
message.setContent(emailBody, "text/html; charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
A way to solve errors when sending an email and, moreover, when you want to do something that has been already done from someone else, is by using a library. Open source libraries are used from a lot of developers and their bugs are all the times less than a custom source code. I would suggest you to use Apache commons Email Library.
Using this link you can find a lot of examples.

sending mail using java from pc to mobile

final String username = "<mail_name>";
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", "465");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("<mail_from>#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("<mail_to>#gmail.com"));
message.setSubject("Test Subject");
message.setText("Test");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
I have tried this code for sending mail from pc to mobile but it giving error while compiling . Can any one help me to send mail?
public class sendmail{
public static void mail(String args[]){
final String fromEmail = ""; //requires valid gmail id
final String password = ""; // correct password for gmail id
final String toEmail = "" // can be any email id
System.out.println("SSLEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
props.put("mail.smtp.port", "465"); //SMTP Port
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
String subject = "";//subject here
String body = "";//mail body here
sendEmail(session, toEmail, subject, body);
}
public static void sendEmail(Session session, String toEmail, String subject, String body) {
try {
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no-reply#anyname.com", "any name"));
msg.setReplyTo(InternetAddress.parse(toEmail, false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("ERROR:" + e.getMessage());
}
}
}
What is mean by PC to Mobile. PC & mobile both are hardware devices to access the mail.Please follow the below link for sending mail in java using java mail API via gmail SMTP.
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

Exception is coming when try to send emal using jsp servlet :javax.mail.internet.AddressException

I try to send emails using jsp. All the things working perfect but when I try to use more than one email addresses it shows error ,
javax.mail.internet.AddressException: Illegal address in string ``
here is my code
public EmailSender(String[] to, String subject, String msg) {
final String txtFromAcc = "abeywicrema#gmail.com";
final String pwfFromPW = "mjkkmqzrkkgsydqk";
String txtFrom = "norply#politeknick.com";
//String txtTo = "abeywicrema#gmail.comshan.a#jinasena.com.lk";//to;
String txtSubject = subject;
String txaMessage = msg;
String[] sendMore = to;//{"abeywicrema#gmail.com", "shan.a#jinasena.com.lk"};
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.debug", "true");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.socketFactory.fallback", "false");
Authenticator auth = new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(txtFromAcc, pwfFromPW);
}
};
Session session = Session.getDefaultInstance(prop, auth);
try {
Message mail = new MimeMessage(session);
mail.setFrom(new InternetAddress(txtFrom));
InternetAddress[] addressTo = new InternetAddress[sendMore.length];
for (int i = 0; i < sendMore.length; i++) {
addressTo[i] = new InternetAddress(sendMore[i]);
}
mail.setRecipients(Message.RecipientType.TO, addressTo);
mail.setSubject(txtSubject);
mail.setContent(txaMessage, "text/plain");
Transport.send(mail);
//OptionPane.showMessageDialog(this, "Sent");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(">>>>>>>>>>>>>>>>msg has been sent ");
}

Categories