Error when sending email via Java Mail API? - java

I got following error when trying to send email via Java Mail API? What does this error mean?
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2210)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
Here is my code, i set all parameters (from, to , subjects and attachments)
public static void send(MailUtil mailUtil) throws MessagingException {
MimeMessage message = new MimeMessage(session);
if (props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_SENDER) != null) {
message.setFrom(new InternetAddress(props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_SENDER)));
} else {
message.setFrom(new InternetAddress(mailUtil.getFrom()));
}
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(mailUtil.getTo()));
if (mailUtil.getBcc() != null && mailUtil.getBcc().trim().length() > 0) {
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mailUtil.getBcc()));
} else {
message.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(""));
}
message.setSubject(mailUtil.getSubject(), "UTF-8");
// Check for files list and attach them.
if (mailUtil.attachmentFiles != null && mailUtil.attachmentFiles.size() > 0) {
Multipart multipart = new MimeMultipart();
// Set content.
BodyPart messageBodyPart =new MimeBodyPart();
messageBodyPart.setContent(mailUtil.getContent(), "text/plain; charset=utf-8");
multipart.addBodyPart(messageBodyPart);
// Attach files.
for (File file : mailUtil.attachmentFiles) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
} else {
//message.setContent("<h1>Hello world</h1>", "text/html");
message.setContent(mailUtil.getContent(), "text/html; charset=UTF-8");
}
Transport.send(message);
}
I just think is there any problem with my paramters?
Belows is my configuration
mail.smtp.port=465
mail.smtp.starttls.enable=true
mail.smtp.auth=true
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.timeout=25000
mail.smtp.host=smtp.gmail.com
mail.username = username#gmail.com
mail.password = mypassword
mail.sender = sender#gmail.com
mail.receiver = receiver#gmail.com
mail.subject = mysubject
I am using google mail server! I dont' think there is problem there!
Belows is session initiation
final String userName = props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_USERNAME);
final String passWord = props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_PASSWORD);
session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName,
passWord);
}
});

I believe it absolutely relates to server configuration.
When I change the port configuration from 465 to 587, it solves my problem!
Anyway, thank you guy for your help!

Your code and configuration contain many of these common mistakes. In particular, the use of Session.getDefaultInstance may mean you're not using the configuration you think you're using. If fixing that doesn't solve your problem, post the JavaMail session debug output.

I'm not sure why you use a "mail" object to setup the connection properties, instead try this, it should work, I've tested myself:
private Properties props;
props = System.getProperties();
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.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
message.setFrom(new InternetAddress("YOUR EMAIL ADDRESS HERE"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("RECEIVER EMAIL ADDRESS HERE"));
message.setSubject("SUBJECT");
message.setText("THE EMAIL TEXT");
Transport.send(message);
} catch (MessagingException e) {e.printStackTrace();}
}

Related

Javamail Body does not appear when together with attachment

So I have the problem with the Javamail where if I send an attachment in the mail the body disappears. When I don't send an attachment with the mail i can just see the body.
My GMailSender.java:
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
_multipart = new MimeMultipart();
}
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception
{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setText(body);
message.setDataHandler(handler);
if(_multipart.getCount() > 0)
message.setContent(_multipart);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}
public void addAttachment(String filename) throws Exception
{
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
My MainActivity.java
Button bt_send = findViewById(R.id.Alert);
bt_send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
BackgroundMail bm = new BackgroundMail(context);
bm.setGmailUserName("***#gmail.com");
bm.setGmailPassword("******");
bm.setMailTo(to);
bm.setFormSubject(value + " DOC/" + mTvResult.getText().toString());
bm.setFormBody("Document Nummer:\n" + mTvResult.getText().toString() + "\n \nDocument Type:\n" + value);
if (images.size() > 0) {
for (Object file : images) {
bm.setAttachment(file.toString());
}
}
bm.setSendingMessage("Loading...");
bm.setSendingMessageSuccess("The mail has been sent successfully.");
bm.send();
}
});
So how can i add an attachment while still being able to see the body itself?
Thanks in advance!
It looks like you copied GMailSender from someone else. You should start by fixing all these common mistakes.
You never call the addAttachment method. (Note that you could replace that method with the MimeBodyPart.attachFile method). Please remember to post the code that you're actually using.
The key insight that you're missing is that for a multipart message the main body part needs to be the first body part in the multipart. Your call to Message.setContent(_multipart); overwrites the message content that was set by your call to message.setDataHandler(handler);, which also overwrote the content set by your call to message.setText(body);.
Instead of setting that content on the message, you need to create another MimeBodyPart, set the content on that MimeBodyPart, and then add that MimeBodyPart as the first part of the multipart.

after sending few emails Could not connect to SMTP host , nested exception is: java.net.ConnectException: Connection refused: connect

I want to get all unread emails from server and send each message to another email. When I send each unread email (Using HostGator), after sending few mails (30-40) an error occurs as I mentioned. This is my sending method. What can i do? I checked with smtp port 25,465,587. but none of them worked. Same error appears. :/ if any one knows how to handle it please let me know. Thank you..
email send method:-
public static void send(String sub,final String user, final String pass, String toMails) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.host", "gator.hostgator.com");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipients(Message.RecipientType.TO, toMails);
message.setSubject(sub);
message.setText("-Body-");
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("-Body-");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
message.setContent(multipart);
Transport.send(message);
}
This is error message :-

Send a table inside of RTF message JavaMail

I'm trying to send a email with a Table in string with RTF, but when I check the email the message body, the table lost the format, so I wondering what I'm doing wrong, this is the following chunk of code to send and email
public static void send(String asunto, String texto, String emailDestinatario){
final String username = "myemail#gmail.com";
final String password = "mypass";
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() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse( emailDestinatario));
message.setSubject(asunto);
message.setText(texto);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
what others configurations I need to send and email and recogniz me the format of table?
This is a document example to send via email
I get something like that(the table lost the format)
TARIFAS EMPLEADOS
TARIFA
IVA
TOTAL
EMPLEADOS HASTA $150.000.000
94,000
15,040
109,040
EMPLEADOS MAYOR DE $150.000.000
160,000
25,600
185,600
Have you tried something like :
MimeMessage message = new MimeMessage(sesion);
.
.
.
//Config your message....
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("RTF HTML TEXT", "text/html");
mp.addBodyPart(htmlPart);
message.setContent(mp);
Transport.send(message);

Sending email using godaddy account using java

I am trying to send emails using my godaddy account in java. Below is my code.
Properties props = System.getProperties();
props.put("mail.transport.protocol","smtp" );
props.put("mail.smtp.starttls.enable","true" );
props.put("mail.smtp.ssl.enable", "false");
props.put("mail.smtp.host","smtpout.secureserver.net");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.port","465");
props.put("mail.debug","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");
Authenticator auth = new SMTPAuthenticator();
Session session=Session.getInstance(props,auth);
session.setDebug(true);
// -- Create a new message --
Transport transport=session.getTransport();
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(""email#domain.com));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("email#domain.com", false));
msg.setSubject("subject");
msg.setText("Message");
transport.connect();
Transport.send(msg);
transport.close();
While executing I'm getting the below Exception.
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtpout.secureserver.net , 465; timeout -1;
nested exception is:
java.net.UnknownHostException: smtpout.secureserver.net
PS:When i use gmail account for authentication its working fine and email sent successfully. When i use godaddy account the exception throws.
Please guide me how to solve this issue...
Thanks in advance...
My configuration in SpringBoot (replace domainname.com to your domainname)
spring:
mail:
host: smtpout.secureserver.net
port: 465
username: info#domainname.com
password: password
protocol: smtp
properties.mail.smtp:
auth: true
ssl.enable: true
ssl.trust: "*"
Also I had to add mimeMessageHelper.setFrom("info#domainname.com"); before sending the mail (else it was taking my system name and gave an error) and this setup worked.
Here is complete method that is working absolutely fine for me (I have also used an attachment in the message) :
private void sendUsingSmtp(MailDetail mailDetail) {
Properties props = new Properties();
props.put("mail.host", "smtpout.secureserver.net");
props.put("mail.port", "465");
props.put("mail.username", "info#domainName.com");
props.put("mail.password", “password”);
props.put("mail.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.trust", "*");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("info#domainName”, “password");
}
});
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress("info#domainName.com", false);
msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(“targetEmail#gmail.com"));
msg.setSubject("Test Subject.");
msg.setContent("Test Content.", "text/html");
msg.setSentDate(new Date());
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("Test Content.", "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
MimeBodyPart attachPart = new MimeBodyPart();
attachPart.attachFile("/var/tmp/abc.txt");
multipart.addBodyPart(attachPart);
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JavaMail SSL with no Authentication trust certificate regardless
MailSSLSocketFactory socketFactory = new MailSSLSocketFactory();
socketFactory.setTrustAllHosts(true);
requires javax.mail 1.5.2 and greater

Send image in Email Body using Java

I have been able to send Image as an Attachment in an Email using Java. I am now trying to send the same image in the Email Body Like this:
public static void main(String[] args) throws NoSuchProviderException, MessagingException {
System.out.println("Sending mail...");
Properties props = new Properties();
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.user", "mysusername");
props.setProperty("mail.smtp.password", "mypassword");
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML mail with images");
message.setFrom(new InternetAddress("myaddress#gmail.com"));
message.setContent
("<h1>This is a test</h1>"
+ "<img src=\"C:/Users/pc/Desktop/Photos/Shammah.PNG\">",
"text/html");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("receiver#simbatech.biz"));
transport.connect();//This is line 46
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
I am getting this output:
Sending mail...
DEBUG: setDebug: JavaMail version 1.4ea
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
Exception in thread "main" javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at image.in.body.ImageInBody.main(ImageInBody.java:46)
Java Result: 1
Why is authentication failing while I am using the correct username and Password for My Gmail account?
see the below code may be use full
class SimpleMail2 {
public static void main(String[] args) throws Exception{
System.out.println("Sending mail...");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
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,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("sender#gmail.com","password");
}
});
Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress("sender#gmail.com"));
message.setSubject("HTML mail with images");
message.setRecipient(Message.RecipientType.TO, new InternetAddress("receiver#gmail.com"));
message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!");
MimeMultipart multipart = new MimeMultipart("related");
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Raghava chary</H1>" + "<img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");
multipart.addBodyPart(messageBodyPart);
try {
messageBodyPart = new MimeBodyPart();
InputStream imageStream = SimpleMail2.class.getClass().getResourceAsStream("/ab/log.gif");
DataSource fds = new ByteArrayDataSource(IOUtils.toByteArray(imageStream), "image/gif");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<image>");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and add org.apache.commons.io.jar.zip and axiom-api-1.2.6.jar and add mail.jar and activation.jar
You need to declare your images like this :
<img src="cid:unique-name-or-id" />
Load images as MimeBodyPart and match the unique-name-or-id with the FileName of the MimeBodyPart.
Create a multipart body with content-disposition inline and encode in base64 your image.
Check this SO for some details (in Python) Sending Multipart html emails which contain embedded images
First, see this JavaMail FAQ entry of common mistakes.
Then, see this JavaMail FAQ entry with sample code for connecting to Gmail.
Note that there is no "mail.smtp.password" property. Since you're not supplying a password, authentication is failing.
Another common mistake (bit me today): the Content-ID header for the image must be in <angle brackets>. Failure to do so will break some mail programs (gmail, OS X 10.10) but not others (Outlook, iOS <= 8.1).

Categories