Send a mail with java and gmail

22,071

Use the below code.

public void sendTemplateEmail() {

        Properties props = new Properties();  
        props.put("mail.smtp.host", "smtp.gmail.com");  
        props.put("mail.smtp.auth", "true");  
        props.put("mail.debug", "true");  
        props.put("mail.smtp.port", 25);  
        props.put("mail.smtp.socketFactory.port", 25);  
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.transport.protocol", "smtp");
        Session mailSession = null;

        mailSession = Session.getInstance(props,  
                new javax.mail.Authenticator() {  
            protected PasswordAuthentication getPasswordAuthentication() {  
                return new PasswordAuthentication("<Gmail User Name>", "<Gmail Password>");  
            }  
        });  


        try {

            Transport transport = mailSession.getTransport();

            MimeMessage message = new MimeMessage(mailSession);

            message.setSubject("Sample Subject");
            message.setFrom(new InternetAddress("[email protected]"));
            String []to = new String[]{"Sample2gmail.com"};
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[0]));
            String body = "Sample text";
            message.setContent(body,"text/html");
            transport.connect();

            transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
            transport.close();
        } catch (Exception exception) {

        }
    }

Replace all the from and to email addresses and the and in the above code.

Share:
22,071
Toni Rodriguez
Author by

Toni Rodriguez

Updated on July 09, 2022

Comments

  • Toni Rodriguez
    Toni Rodriguez almost 2 years

    I wanto to send a e-mail with an calendar attachment javaxmail and I created this class:

    public void sendEmail(String to, Calendar calendar) {
        try {
            String  d_uname = "[email protected]";
            String    d_password = "mypassword";
            String d_host = "smtp.gmail.com";
            String  d_port  = "587";//465,587
    
            String from = "[email protected]";
    
            String subject = "Subject";
            String bodyText = "Body";
    
            Properties prop = new Properties();
    
            //prop.setProperty("mail.smtp.auth", "true");
            prop.setProperty("mail.smtp.host", "smtp.gmail.com");
            prop.setProperty("mail.smtp.protocol", "smtps");
            prop.setProperty("mail.smtp.starttls.enable", "true");
            prop.setProperty("mail.smtp.ssl.enable", "true");
            prop.setProperty("mail.smtp.port",d_port);
            prop.setProperty("mail.smtp.user", d_uname);
    
    
            Session session = Session.getDefaultInstance(prop, null);
            // Define message
            session.setDebug(true);
            MimeMessage message = new MimeMessage(session);
            message.addHeaderLine("method=REQUEST");
            message.addHeaderLine("charset=UTF-8");
            message.addHeaderLine("component=VEVENT");
    
    
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("Outlook Meeting Request Using JavaMail");
    
            StringBuffer sb = new StringBuffer();
    
            StringBuffer buffer = sb.append(calendar.toString());
    
            // Create the message part 
            BodyPart messageBodyPart = new MimeBodyPart();
    
            // Fill the message 
            messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
            messageBodyPart.setHeader("Content-ID","calendar_message");
            messageBodyPart.setDataHandler(new DataHandler(
                    new ByteArrayDataSource(buffer.toString(), "text/calendar")));//very important
    
    
            // Create a Multipart 
            Multipart multipart = new MimeMultipart();
    
            // Add part one 
            multipart.addBodyPart(messageBodyPart);
    
            Transport t = session.getTransport("smtp");
            t.connect(d_host, 587, d_uname, d_password);
    
    
            // Put parts in message 
            message.setContent(multipart);
    
            // send message 
            t.send(message);
        } catch (MessagingException me) {
            me.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    

    It seems ok, but, when I try to send, the console shows this error:

    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
    DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
      nested exception is:
        java.net.SocketException: Permission denied: connect
    

    Can someone help me? Thanks in advance!!

  • Toni Rodriguez
    Toni Rodriguez over 10 years
    This code shows the same error that my code. "Permission denied: connect". Thanks¡ I don't understand what is worng.
  • SmartTechie
    SmartTechie over 10 years
    I tested the code. It is working perfectly. Can you post the error message what your getting? For authentication, you need to provide your gmail address and the password.
  • Toni Rodriguez
    Toni Rodriguez over 10 years
    this is the trace of my error. ## DEBUG: setDebug: JavaMail version 1.4ea DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTra‌​nsport,Sun Microsystems, Inc] DEBUG SMTP: useEhlo true, useAuth true DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.SocketException: Permission denied: connect at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.jav‌​a:1282) at com.sun.mail.smtp.SMTPTransport.protocolCo..
  • Toni Rodriguez
    Toni Rodriguez over 10 years
    Can you test my code to check if it is rigth? If then, it could be network problem..
  • SmartTechie
    SmartTechie over 10 years
    Can you change the port from 587 to 25? Looks like, port 587 is not opened.
  • Toni Rodriguez
    Toni Rodriguez over 10 years
    Oh no, it isn't the problem. The conection is already refuse with the same error.
  • SmartTechie
    SmartTechie over 10 years
    Can you do telnet smtp.gmail.com:587? and see whether the connection is established or not?
  • SmartTechie
    SmartTechie over 10 years
    Run my code and see whether, we able to receive the mail or not? Then, you can modify the code according to your requirement.
  • Toni Rodriguez
    Toni Rodriguez over 10 years
    I can´t conect telent to smtp.gmail.com with 587 por, the console shows "conection closes by remote host" and "Permission denied". As I was suposed, it should be network problem