Javax.mail.MessagingException:

package com.mca2b;
import java.util.Properties;
import javax.mail.util.*;
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;  


public class SampleMail 
{
     public static void main(String [] args) throws Exception{  
          String to = "kalgaonkarsiddhesh@gmail.com";//change accordingly  
          String from = "siddhesh.kalgaonkar@ves.ac.in";//change accordingly  
          String host = "localhost";//or IP address  
          // Get system properties
          Properties properties = System.getProperties();

          // Setup mail server
          properties.setProperty("mail.smtp.host", host);

          // Get the default Session object.
          Session session = Session.getDefaultInstance(properties);

          try{
             // Create a default MimeMessage object.
             MimeMessage message = new MimeMessage(session);

             // Set From: header field of the header.
             message.setFrom(new InternetAddress(from));

             // Set To: header field of the header.
             message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));

             // Set Subject: header field
             message.setSubject("This is the Subject Line!");

             // Now set the actual message
             message.setText("This is actual message");

             // Send message
             Transport.send(message);
             System.out.println("Sent message successfully....");
          }catch (SendFailedException mex) {
             mex.printStackTrace();
          }

     }  

}

      

I am getting an exception on the "main" thread javax.mail.MessagingException. Failed to connect to SMTP host: localhost, port: 25 nested exception: java.net.ConnectException: Connection failed: connect. So what is this solution for?

I am posting the correct code here for sending mail via gmail in struts 2. For different providers, you will need to change the SMTP host accordingly :)

package org.entity;

import com.opensymphony.xwork2.ActionSupport;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class DonorForgotAction extends ActionSupport
{
DonorForgot forg;
    public DonorForgotAction() {
    // TODO Auto-generated constructor stub
}
    public DonorForgot getForg() {
        return forg;
    }
    public void setForg(DonorForgot forg) {
        this.forg = forg;
    }
    @Override
    public String execute() throws Exception {
        String email,pass;
        final String username = "";
        final String 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() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/foryou", "root", "siddheshkk");
            System.out.println("Driver Loaded");
            PreparedStatement ps = con
                    .prepareStatement("select email,password from donorinfo where contact=?");
            ps.setString(1, forg.getContact());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                email=rs.getString("email");
                pass=rs.getString("password");
                System.out.println("Here is your email id "+email+"and password is "+pass);
                try {
                    Message message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(username));
                    message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(email));
                    message.setSubject("Password Retrieval");
                    message.setText("Dear user your password is "+ pass);
                    Transport.send(message);
                    System.out.println("Done");

                } catch (MessagingException e) {
                    e.printStackTrace();
                }
                return "success";
            } else {
                return "error";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

}

      

+3


source to share


1 answer


You forgot two steps:

  • your password

  • Authenticator

Also, it is possible that you did not have a local mail server listening on port 25 on your localhost (javax.mail.MessagingException).

Here I am using port 587.

So try this code:



import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class SampleMail 
{
     public static void main(String [] args) throws Exception
     {  
          final String from = "siddhesh.kalgaonkar@ves.ac.in"; // change accordingly
          final String password = "yourPassword"; // change accordingly
          String to = "kalgaonkarsiddhesh@gmail.com"; // change accordingly
          String host = "localhost"; // or IP address

          // Get system properties
          Properties properties = System.getProperties();

          // Setup mail server
          properties.put("mail.smtp.host", host);
          properties.put("mail.smtp.port", 587);
          properties.put("mail.smtp.auth", "true");
          properties.put("mail.smtp.starttls.enable", "true");
          properties.put("mail.user", from);
          properties.put("mail.password", password);

          // Get the default Session object.
          Authenticator auth = new Authenticator()
          {
              public PasswordAuthentication getPasswordAuthentication()
              {
                  return new PasswordAuthentication(from, password);
              }
          };
          Session session = Session.getInstance(properties, auth);

          try
          {
             // Create a default MimeMessage object.
             MimeMessage message = new MimeMessage(session);

             // Set From: header field of the header.
             message.setFrom(new InternetAddress(from));

             // Set To: header field of the header.
             message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));

             // Set Subject: header field
             message.setSubject("This is the Subject Line!");

             // Now set the actual message
             message.setText("This is actual message");

             // Send message
             Transport.send(message);
             System.out.println("Sent message successfully....");
          }
          catch (SendFailedException mex)
          {
             mex.printStackTrace();
          }
     }
}

      

I am using this code if it helps you:

import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


class SampleMail
{
    public static void main(String args[]) throws Exception
    {
        new Email("yourEmail(sendTheMessage)", "yourEmailPassword", "yourEmail(recvTheMessage)", "subject", "message"); // Send a message

        String[] attachments = {"/home/user/Documents/text.odt"};
        new Email("yourEmail(sendTheMessage)", "yourEmailPassword", "yourEmail(recvTheMessage)", "subject", "message", attachments); // send a message with attachments
    }
}

class Email
{
    private String host, port = "587";

    Email(String mailFrom, String password, String mailTo, String subject, String message) throws Exception
    {
        if (mailFrom.contains("@gmail"))
            this.host = "smtp.gmail.com";
        else if (mailFrom.contains("@yahoo"))
            this.host = "smtp.mail.yahoo.com";
        else
            this.host = "smtp.live.com";

        sendEmail(host, port, mailFrom, password, mailTo, subject, message, null);
    }

    Email(String mailFrom, String password, String mailTo, String subject, String message, String[] attachFiles) throws Exception
    {
        if (mailFrom.contains("@gmail"))
            this.host = "smtp.gmail.com";
        else if (mailFrom.contains("@yahoo"))
            this.host = "smtp.mail.yahoo.com";
        else
            this.host = "smtp.live.com";

        sendEmail(host, port, mailFrom, password, mailTo, subject, message, attachFiles);
    }

    private void sendEmail(String host, String port, final String userName, final String password, String toAddress, String subject, String message, String[] attachFiles) throws Exception
    {
        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);

        Authenticator auth = new Authenticator()
        {
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(userName, password);
            }
        };
        Session session = Session.getInstance(properties, auth);

        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(userName));
        InternetAddress[] toAddresses = {new InternetAddress(toAddress)};
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(message, "text/html");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        if (attachFiles != null && attachFiles.length > 0)
        {
            for (String filePath : attachFiles)
            {
                MimeBodyPart attachPart = new MimeBodyPart();

                try
                {
                    attachPart.attachFile(filePath);
                }
                finally
                {
                    multipart.addBodyPart(attachPart);
                }
            }
        }
        msg.setContent(multipart);

        Transport.send(msg);
    }
}

      

But here you have to change the host to allow something else besides the gmail, yahoo or hotmail account.

+1


source







All Articles