Strange characters seen when sending mail in Italian language using Javamail - jakarta-mail

Strange characters seen after equal to sign when sending mail in Italian language using Javamail. Could anyone suggest code to send mail in italian language using javamail?
Email body is as below
Ciao Dibyendu Biswas,
Abbiamo ricevuto una richiesta di reimpostazione della sua password Validac=
tor.
Rei=
mposta Password
Se ignori questo messaggio, la password non verr=C3=A0 reimpostata.
Se non hai richiesto la reimpostazione della password, Comunicacelo
Below is the java mail code I am using to send mail.
public static boolean sendMail (String emailId,String subject,String body,boolean isHtml) {
boolean status = false;
Properties properties = new Properties();
properties.setProperty("mail.smtp.host", "smtp.zoho.com");
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
properties.setProperty("mail.smtp.port", "465");
properties.setProperty("mail.smtp.socketFactory.port", "465");
properties.setProperty( "mail.pop3.socketFactory.fallback", "false");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.debug", "true");
properties.put("mail.store.protocol", "pop3");
properties.put("mail.transport.protocol", "smtp");
properties.put("mail.debug.auth", "true");
javax.mail.Session session = javax.mail.Session.getInstance(properties,new javax.mail.Authenticator()
{ #Override
protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication(ProductValidationSystemWebConstants.VALIDACTOR_SUPPORT_EMAILID,ProductValidationSystemWebConstants.VALIDACTOR_SUPPORT_PASSWORD);
}
});
try
{ MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(ProductValidationSystemWebConstants.VALIDACTOR_SUPPORT_EMAILID));
message.setRecipients(MimeMessage.RecipientType.TO,InternetAddress.parse(emailId));
message.setSubject(subject);
if(isHtml) {
System.out.println("mail body before: "+body);
message.setText(body,"UTF-8", "html");
System.out.println("mail body after: "+body);
}
else
message.setText(body);
Transport.send(message);
status = true;
}
catch (MessagingException e)
{
e.printStackTrace();
}
return status;
}
I use gmail to read the mail. Issue happens when there is any Italian character in the mail content.

Related

Javamail send message from 2 smtp servers

I have a problem and need some help
In my program I need to send a mail and smtp server depends of one var,
if var is 1 then must send mail from a gmail address
or if var is 2 the mail is send from a diferent smtp server
I use TLS from both accounts and all is ok (if only send from 1 server)... but when I try to send from both servers (because my var change depend from 1 to 2, or 2 to 1 many times during the execution) I recieved always an error
Here my code:
public static void correo(String empresa, String[] dest, String archivo, String nom_arch){
String cuenta = "", asunto = "", pw = "", pto = "", server = "";
try
{
Properties props = new Properties();
if("1".equals(empresa)){
cuenta = "example#gmail.com";
asunto = "xxxxxxx";
pw = "password";
pto = "587";
server = "smtp.gmail.com";
}
else if ("2".equals(empresa)) {
cuenta = "example#server.com";
asunto = "yyyyyyy";
pw = "password";
pto = "25";
server = "smtpout.secureserver.net";
}
props.setProperty("mail.smtp.host", server);
props.setProperty("mail.smtp.port", pto);
props.setProperty("mail.smtp.user", cuenta);
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props,null);
BodyPart texto = new MimeBodyPart();
texto.setText("Some Text");
BodyPart adjuntoPDF = new MimeBodyPart();
adjuntoPDF.setDataHandler(new DataHandler(new FileDataSource(archivo+".pdf")));
adjuntoPDF.setFileName(nom_arch+".pdf");
MimeMultipart multiparte = new MimeMultipart();
multiparte.addBodyPart(texto);
multiparte.addBodyPart(adjuntoPDF);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(cuenta));
InternetAddress[] direcciones = new InternetAddress[dest.length];
for(int i=0; i<dest.length; i++){
direcciones[i] = new InternetAddress(dest[i]);
}
message.addRecipients(Message.RecipientType.TO,direcciones);
message.setSubject(asunto);
message.setContent(multiparte);
Transport t = session.getTransport("smtp");
t.connect(cuenta, pw);
t.sendMessage(message, message.getAllRecipients());
t.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
See this JavaMail FAQ list of common JavaMail mistakes. Change Session.getDefaultInstance to Session.getInstance.

Office365 JavaMail error

I have a Java class that works perfectly to send emails with a Gmail account. However, I've used the recomended SMTP settings, there is an error when I try to send an email with an Office365 account. The error returned is this:
exception
javax.servlet.ServletException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.office365.com, port: 587;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
Below is my code:
public class GmailBean {
public static final String SERVIDOR_SMTP = "smtp.office365.com";
public static final int PORTA_SERVIDOR_SMTP = 587;
private static final String CONTA_PADRAO = "xxx#xxx.com";
private static final String SENHA_CONTA_PADRAO = "xxx";
private String de;
private String para;
private String assunto;
private String mensagem;
public void enviarEmail() throws MessagingException {
FacesContext context = FacesContext.getCurrentInstance();
AutenticaUsuario autenticaUsuario = new AutenticaUsuario(GmailBean.CONTA_PADRAO, GmailBean.SENHA_CONTA_PADRAO);
Session session = Session.getInstance(this.configuracaoEmail(), autenticaUsuario);
// try{
Transport envio = null;
MimeMessage email = new MimeMessage(session);
email.setRecipient(Message.RecipientType.TO, new InternetAddress(this.para));
email.setFrom(new InternetAddress(this.de));
email.setSubject(this.assunto);
email.setContent(this.mensagem, "text/plain");
email.setSentDate(new Date());
envio = session.getTransport("smtp");
envio.connect(GmailBean.SERVIDOR_SMTP, GmailBean.CONTA_PADRAO, GmailBean.SENHA_CONTA_PADRAO);
email.saveChanges();
envio.sendMessage(email, email.getAllRecipients());
envio.close();
context.addMessage(null, new FacesMessage("Mensagem enviada com sucesso!"));
/* }
catch(AddressException ex)
{ Logger logger = Logger.getAnonymousLogger();
FacesMessage msg = new FacesMessage("Erro ao enviar mensagem "+ ex.getMessage());
logger.info("Erro ao enviar mensagem _____________"+ ex.getMessage());
}
catch(MessagingException ex)
{
Logger logger = Logger.getAnonymousLogger();
FacesMessage msg = new FacesMessage("Erro ao enviar mensagem "+ ex.getMessage());
logger.info("Erro ao enviar mensagem _____________"+ ex.getMessage());
}*/
}
public Properties configuracaoEmail() {
Properties config = new Properties();
config.put("mail.smtp.auth", "true");
config.put("mail.transport.protocol", "smtp");
config.put("mail.smtp.starttls.enabled", "true");
config.put("mail.smtp.host", SERVIDOR_SMTP);
config.put("mail.user", GmailBean.CONTA_PADRAO);
config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
config.put("mail.smtp.socketFactory.port", PORTA_SERVIDOR_SMTP);
config.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
config.put("mail.smtp.socketFactory.fallback", "false");
return config;
}
// (Getters and setters... )
class AutenticaUsuario extends Authenticator {
private String usuario;
private String senha;
public AutenticaUsuario(String usuario, String senha) {
this.usuario = usuario;
this.senha = senha;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(this.usuario, this.senha);
}
}
Fix all these common mistakes and it should work.
The JavaMail FAQ entry for outlook.com should work for Office365 as well by changing the host name.

sending mail using javamail getting authentication issue

When I tried to send mail using following code, I got authentication issues.
Here's my code:
public class NewSendMail {
String to = "********";
String subject = "subject";
String msg ="email text....";
final String from ="*******";
final String password ="******";
public NewSendMail(){
}
public boolean sendMymail(){
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
// Session session = Session.getDefaultInstance(props);
//session.setDebug(true);
Transport transport;
InternetAddress addressFrom = null;
try {
transport = session.getTransport();
addressFrom = new InternetAddress(from);
MimeMessage message = new MimeMessage(session);
message.setSender(addressFrom);
message.setSubject(subject);
message.setContent(msg, "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
transport.connect();
Transport.send(message);
transport.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
It is throwing a javax.mail.AuthenticationFailedException.
How can I fix the issue?
The following code may help you
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();
}
}
}
This code worked for me, If it is not working for you, Check your jar files
I tell everyone who asks for JavaMail help the same things. (I wonder why they call it a FAQ?)
Fix these common mistakes.
Follow this example for Gmail.
Turn on session debugging to get more details of what's going wrong, and post the output if you still can't figure it out.
Either you're sending the wrong username or password, or the server is rejecting your login attempt for other reasons, perhaps because you haven't enabled less secure apps.

JAVAMAIL + ERROR + Connection closed by remote host

I'm trying to send mass emails, Achievement send 20 emails on average and then I get this error:
javax.mail.MessagingException: Can't send command to SMTP host; nested exception is: java.net.SocketException: Connection closed by remote host
CODE JAVA:
public void mandarEmail(String correos, String mensaje, String asunto) {
final String username = "docs-gf#usmp.pe";
final String password = "Docpass";
Message message;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.host", "pod51004.outlook.com");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
message = new MimeMessage(session);
message.setFrom(new InternetAddress("Hello my friend"));
message.setSubject("I love u very much");
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("ivan#hotmail.com"));
message.setContent(mensaje, "text/html; charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
} finally {
props = null;
message = null;
}
}
I'm forgetting something?
Probably the server doesn't want you to send mass emails and so is rate limiting you. Turn on JavaMail Session debugging and there might be more information from the server in the protocol trace.

How to write the body part while sending an email?

While sending the email after the script completed i am not able to add any body part. I want to add body like,
Hi xyz,
Please find the attached the reports attached.
With Best Regards,
Abc.
I am using the below code for sending the email . Can anyone please guide me how to send email.
package util;
//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendMail
{
public static void zipAndSendReport()
{
TestUtil.zip(System.getProperty("user.dir") +"\\HtmlReports");
String[] to={"xyz#xyz.com"};
String[] cc={"xyzff#xyz.com","xyzaa#xyz.com"};
String[] bcc={"xyzrwer#xyz.com"};
//This is for google
SendMail.sendMail("acv.ddg#gmail.com",
"070122dasdad3183",
"smtp.gmail.com",
"465",
"true",
"true",
true,
"javax.net.ssl.SSLSocketFactory",
"false",
to,
cc,
bcc,
"Automation test Reports",
"Please find the reports attached.\n\n Regards\nWebMaster",
System.getProperty("user.dir")+"\\Reports.zip",
"Reports.zip");
}
public static boolean sendMail(String userName,
String passWord,
String host,
String port,
String starttls,
String auth,
boolean debug,
String socketFactoryClass,
String fallback,
String[] to,
String[] cc,
String[] bcc,
String subject,
String text,
String attachmentPath,
String attachmentName){
Properties props = new Properties();
//Properties props=System.getProperties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if(!"".equals(port))
props.put("mail.smtp.port", port);
if(!"".equals(starttls))
props.put("mail.smtp.starttls.enable",starttls);
props.put("mail.smtp.auth", auth);
// props.put("mail.smtps.auth", "true");
if(debug){
props.put("mail.smtp.debug", "true");
}else{
props.put("mail.smtp.debug", "false");
}
if(!"".equals(port))
props.put("mail.smtp.socketFactory.port", port);
if(!"".equals(socketFactoryClass))
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
if(!"".equals(fallback))
props.put("mail.smtp.socketFactory.fallback", fallback);
try
{
//Session session = Session.getDefaultInstance(props, null);
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication("acv.ddg#gmail.com","070122sd3183"); }
});
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
//attachment start
// create the message part
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(attachmentPath);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(attachmentName);
multipart.addBodyPart(messageBodyPart);
// attachment ends
// Put parts in message
msg.setContent(multipart);
msg.setFrom(new InternetAddress(userName));
for(int i=0;i<to.length;i++){
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
}
for(int i=0;i<cc.length;i++){
msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
}
for(int i=0;i<bcc.length;i++){
msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
}
catch (Exception mex)
{
mex.printStackTrace();
return false;
}
}
}
Please let us know will this code work or is there any better way of doing this?
Thanks,
Sudhansu
Your MimeMessage can either have text set via setText() or a multipart-body.
Since your use atteachments you have to use multipart. To add some plain text to the message create another MimeBodyPart and add it as the first to your Multipart:
....
Multipart multipart = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(text);
mmp.addBodyPart(textPart);
MimeBodyPart messageBodyPart = new MimeBodyPart();
....

Resources