11 Replies Latest reply: Dec 19, 2011 1:38 PM by DrClap RSS

    Sending mail using Gmail Server.

    834970
      Hi Team,

      I want to send email using Gmail server by writing java Code.

      I am trying using below code:-

      public void send(){
      String host = "smtp.gmail.com";
      String userid = "Gmail User Id";
      String password = "password of gmail id";
      try
      {
      Properties props = System.getProperties();
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", host);
      props.setProperty("mail.transport.protocol", "smtps");
      props.put("mail.smtp.user", userid);
      props.put("mail.smtp.password", password);
      props.put("mail.smtp.port", "465");
      props.put("mail.smtps.auth", "true");
      Session session = Session.getDefaultInstance(props, null);
      MimeMessage message = new MimeMessage(session);
      InternetAddress fromAddress = null;
      InternetAddress toAddress = null;

      try {
      fromAddress = new InternetAddress(from);
      toAddress = new InternetAddress(to);
      } catch (AddressException e) {

      e.printStackTrace();
      }
      message.setFrom(fromAddress);
      message.setRecipient(RecipientType.TO, toAddress);
      message.setSubject(subject);
      message.setText(text);

      //SMTPSSLTransport transport =(SMTPSSLTransport)session.getTransport("smtps");

      Transport transport = session.getTransport("smtps");
      transport.connect(host, userid, password);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
      } catch (MessagingException e) {
      e.printStackTrace();
      }
      }

      And getting error on like :- javax.mail.MessagingException: Could not connect to SMTP host: smtp.mail.com, port: 25;

      I ping in my command prompt :- ping smpt.gmail.com 465. I am able to ping but when I am doing telnet its saying not connecting.


      Can anybody help me in this by sharing some code snippet.

      Thanks in Advance.

      Thanks,
      Ramit
        • 1. Re: Sending mail using Gmail Server.
          Kayaman
          They seemed to succeed in it:
          http://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail
          • 2. Re: Sending mail using Gmail Server.
            845348
            import com.app.constants.Constants;


            import java.io.*;
            import java.util.Properties;
            import javax.activation.DataHandler;
            import javax.activation.DataSource;
            import javax.mail.Message;
            import javax.mail.Session;
            import javax.mail.Transport;
            import javax.mail.internet.InternetAddress;
            import javax.mail.internet.MimeMessage;

            public class ActivationMail {

            public boolean sendMail() {
            boolean hasSend = false;
            try {
            String to = regbean.getEmail();

            //Mailin credentilas extracted from a constant file

            String from = Constants.MAIL_FROM;
            String pass = Constants.MAIL_PASSWORD;
            String host = Constants.MAIL_HOST;


            Properties props = System.getProperties();
            props.put("mail.smtp.starttls.enable", "true"); // added this line gmail account
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.user", from);
            props.put("mail.smtp.password", pass);
            props.put("mail.smtp.port", "25");
            props.put("mail.smtp.auth", "true");



            Session session = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));

            InternetAddress toAddress = new InternetAddress(to);


            message.addRecipient(Message.RecipientType.TO, toAddress);


            String Text = "Test mailing message";

            message.setSubject("Test mail");



            message.setDataHandler(new DataHandler(new ByteArrayDataSource(Text.toString(), "text/html")));

            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            hasSend = true;
            } catch (Exception e) {
            System.out.println("Exception in sending Activation mail = " + e);
            }
            return hasSend;
            }

            // No need of this calss it can be implemented in other ways too

            class ByteArrayDataSource implements DataSource {

            private byte[] data; // data
            private String type; // content-type

            /* Create a DataSource from an input stream */
            public ByteArrayDataSource(InputStream is, String type) {
            this.type = type;
            try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int ch;

            while ((ch = is.read()) != -1) {
            os.write(ch);
            }
            data = os.toByteArray();

            } catch (IOException ioex) {
            }
            }

            /* Create a DataSource from a byte array */
            public ByteArrayDataSource(byte[] data, String type) {
            this.data = data;
            this.type = type;
            }

            /* Create a DataSource from a String */
            public ByteArrayDataSource(String data, String type) {
            try {
            // Assumption that the string contains only ASCII
            // characters! Otherwise just pass a charset into this
            // constructor and use it in getBytes()
            this.data = data.getBytes("iso-8859-1");
            } catch (UnsupportedEncodingException uex) {
            }
            this.type = type;
            }

            public InputStream getInputStream() throws IOException {
            if (data == null) {
            throw new IOException("no data");
            }
            return new ByteArrayInputStream(data);
            }

            public OutputStream getOutputStream() throws IOException {
            throw new IOException("cannot do this");
            }

            public String getContentType() {
            return type;
            }

            public String getName() {
            return "dummy";
            }
            }
            }
            • 3. Re: Sending mail using Gmail Server.
              905511
              // Code for sending mail through java application
              //just make a class mail and run this with command line Interface

              import java.util.Properties;

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

              public class mail {
              String d_email = "khandhar.nilay@gmail.com",
              d_passwd = "Don't try",
              d_host = "smtp.gmail.com",
              d_port = "465", OR "25"
              m_to = "yp_lay@yahoo.com",
              m_subject = "subject",
              m_text = "this is just a test mail";

              public mail() {
              Properties props = new Properties();
              props.put("mail.smtp.user", d_email);
              props.put("mail.smtp.host", d_host);
              props.put("mail.smtp.password", d_passwd);
              props.put("mail.smtp.port", d_port);
              props.put("mail.smtp.starttls.enable","true");
              props.put("mail.smtp.auth", "true");
              //props.put("mail.smtp.debug", "true");
              props.put("mail.smtp.socketFactory.port", d_port);
              props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
              props.put("mail.smtp.socketFactory.fallback", "false");

              //SecurityManager security = System.getSecurityManager();

              try {
              Authenticator auth = new SMTPAuthenticator();
              Session session = Session.getInstance(props, auth);
              //session.setDebug(true);

              MimeMessage msg = new MimeMessage(session);
              msg.setText(m_text);
              msg.setSubject(m_subject);
              msg.setFrom(new InternetAddress(d_email));
              msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
              Transport.send(msg);
              System.out.println("Mail sent");
              } catch (Exception mex) {
              mex.printStackTrace();
              }
              }
              private class SMTPAuthenticator extends javax.mail.Authenticator {
              public PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication(d_email, d_passwd);
              }
              }

              public static void main(String[] args){
              mail sendmail=new mail();
              }
              }


              This is a working example of sending mail through your authenticated email ID.

              Please make the note this way of sending mail is not secure. You need to put some security implemented in java.

              Regards,

              Nilay KHANDHAR
              Java Developer

              Edited by: user10724877 on Dec 15, 2011 4:58 PM
              • 4. Re: Sending mail using Gmail Server.
                834970
                Thanks Nilay, Will try and get back to you on this.

                As you mentioned its not a secure way then could you please tell me what will be the best way to add some security into this.

                thanks in advance.

                thanks,
                ramit
                • 5. Re: Sending mail using Gmail Server.
                  834970
                  Hi Nilay,


                  I did same u mentioned above:-


                  package view.java;

                  import javax.mail.*;
                  import javax.mail.internet.*;
                  import javax.mail.Authenticator;

                  import javax.activation.*;

                  import java.io.*;

                  import java.util.Properties;

                  public class SendMail {
                  public SendMail() {
                  super();
                  }

                  String d_email = "something@gmail.com";
                  String d_passwd = "something";
                  String d_host = "smtp.gmail.com";
                  String d_port = "465"; // OR "25";
                  String m_to = "somethingFrom@yahoo.co.in";
                  String m_subject = "subject";
                  String m_text = "this is just a test mail";

                  public static void main(String[] args) throws MessagingException {
                  SendMail sm = new SendMail();
                  sm.sendMailNow();
                  }

                  public void sendMailNow() throws MessagingException {
                  Properties props = new Properties();
                  props.put("mail.smtp.user", d_email);
                  props.put("mail.smtp.host", d_host);
                  props.put("mail.smtp.password", d_passwd);
                  props.put("mail.smtp.port", d_port);
                  props.put("mail.smtp.starttls.enable", "true");
                  props.put("mail.smtp.auth", "true");
                  //props.put("mail.smtp.debug", "true");
                  props.put("mail.smtp.socketFactory.port", d_port);
                  props.put("mail.smtp.socketFactory.class",
                  "javax.net.ssl.SSLSocketFactory");
                  props.put("mail.smtp.socketFactory.fallback", "false");

                  //SecurityManager security = System.getSecurityManager();

                  try {
                  Authenticator auth = new SMTPAuthenticator();
                  Session session = Session.getInstance(props, auth);
                  //session.setDebug(true);

                  MimeMessage msg = new MimeMessage(session);
                  msg.setText(m_text);
                  msg.setSubject(m_subject);
                  msg.setFrom(new InternetAddress(d_email));
                  msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
                  Transport.send(msg);
                  System.out.println("Mail sent");
                  } catch (Exception mex) {
                  mex.printStackTrace();
                  }

                  }
                  private class SMTPAuthenticator extends javax.mail.Authenticator {
                  public PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(d_email, d_passwd);
                  }
                  }


                  }


                  But I am getting exception like :- unable to find valid certification path to requested target


                  Please suggest me where I am lacking.

                  Thanks in Advance.

                  Regards,

                  Ramit
                  • 6. Re: Sending mail using Gmail Server.
                    DrClap
                    The JavaMail FAQ has a section specifically about using Gmail.

                    Since you couldn't be bothered to format any of your code, I can't be bothered to look at any of it to see if it matches that FAQ entry.
                    • 7. Re: Sending mail using Gmail Server.
                      834970
                      Hi,

                      Can anybody tell me where my code is failing or what i need to do next.

                      Please share something its very urgent for me.

                      Thanks,
                      Ramit
                      • 8. Re: Sending mail using Gmail Server.
                        834970
                        Hi Team,

                        Please share some idea or clue so I can move forward.

                        Thanks,
                        Ramit
                        • 9. Re: Sending mail using Gmail Server.
                          gimbal2
                          did you even see DrClap's post?
                          • 10. Re: Sending mail using Gmail Server.
                            834970
                            Hi,

                            I have gone through DrClap's post, i have seen the FAQ of sending mail through Gmail server. But that doesnt gives us complete details. I matched my code with FAQ and the code which FAQ mentioned. But still the problem is same.

                            Same error :- unable to find valid certification path to requested target

                            If anybody can share some code for the same which is in running state.

                            Please help me.

                            Thanks in advance.

                            Thank,
                            Ramit Mathur
                            • 11. Re: Sending mail using Gmail Server.
                              DrClap
                              The FAQ entry doesn't mention anything about socket factories. The last code you posted uses one. Did you even read the FAQ?

                              If you're looking for code then the smtpsend program which comes as an example with the JavaMail download is that code. Look at the parameters in the JavaMail FAQ and see what effect it has on the way that the smtpsend program runs. You are a Java programmer, right?

                              Or you could continue to beg for somebody to write your code for you. I'm not going to do that.