0

Recently, I made web application in Java netbeans and I made registration and login system, can you tell me please how to send an email using java, so when the user register he will receive a welcome message in his email. I just want the code for sending an email.

hyde
  • 60,639
  • 21
  • 115
  • 176
user2284478
  • 3
  • 1
  • 2
  • 5
  • possible duplicate of [Send email using java](http://stackoverflow.com/questions/3649014/send-email-using-java) – Jim Garrison Apr 15 '13 at 23:52
  • Does this answer your question? [Send email using java](https://stackoverflow.com/questions/3649014/send-email-using-java) – zoldxk Apr 30 '21 at 19:48

4 Answers4

1

Cribbed from here:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;

public class SendMailUsingAuthentication
{
  private static final String SMTP_HOST_NAME = "gemini.jvmhost.com"; //or simply "localhost"
  private static final String SMTP_AUTH_USER = "me@domain.com";
  private static final String SMTP_AUTH_PWD  = "secret";
  private static final String emailMsgTxt      = "Body";
  private static final String emailSubjectTxt  = "Subject";
  private static final String emailFromAddress = "me@domain.com";

  // Add List of Email address to who email needs to be sent to
  private static final String[] emailList = {"he@domain.net"};

  public static void main(String args[]) throws Exception
  {
    SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
    smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
    System.out.println("Sucessfully Sent mail to All Users");
  }

  public void postMail( String recipients[ ], String subject,
    String message , String from) throws MessagingException, AuthenticationFailedException
  {
    boolean debug = false;

    //Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++)
    {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
 }

private class SMTPAuthenticator extends javax.mail.Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        String username = SMTP_AUTH_USER;
        String password = SMTP_AUTH_PWD;
        return new PasswordAuthentication(username, password);
    }
}
}

If you need further assistance, let me know and I'll help.

hd1
  • 33,938
  • 5
  • 80
  • 91
1
 public static void main(String[] args){
        final String fromEmail = "from Emailid";//user.getFromEmail(); //requires valid gmail id
        final String password = " password of from emailid";//user.getPassword(); // correct password for gmail id
         final String toEmail = "to emailid"; // can be any email id 

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
        props.put("mail.smtp.port", "587"); //TLS Port
        props.put("mail.smtp.auth", "true"); //enable authentication
        props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
         //enable authentication
               try
        {
                Authenticator auth = new Authenticator() {
            //override the getPasswordAuthentication method
                        @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail, password.toCharArray());
            }
        };
                Session session = Session.getDefaultInstance(props,null);
          MimeMessage msg = new MimeMessage(session);
          //set message headers
          msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
          msg.addHeader("format", "flowed");
          msg.addHeader("Content-Transfer-Encoding", "8bit");

          msg.setFrom(new InternetAddress(fromEmail, "Rameshwar Agarwal"));

          msg.setReplyTo(InternetAddress.parse(fromEmail, false));

          msg.setSubject("app test email", "UTF-8");

          msg.setText("hello Rameshwar", "UTF-8");

          msg.setSentDate(new Date());

          msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
          System.out.println("Message is ready");
              Transport trans=session.getTransport("smtp");
              trans.connect("smtp.gmail.com",fromEmail,password);
              trans.sendMessage(msg,msg.getAllRecipients());

          System.out.println("EMail Sent Successfully!!");
        }
        catch (Exception e) {
          e.printStackTrace();
        }
}

Don't forget to download java mail api from

THess
  • 1,003
  • 1
  • 13
  • 21
0

From this question:

The following code works very well with Google SMTP server. You need to supply your Google username and password. (Don't forget to download the JavaMail API)

import com.sun.mail.smtp.SMTPTransport;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GoogleMail {
    private GoogleMail() {
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param title title of the message
     * @param message message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException {
        GoogleMail.Send(username, password, recipientEmail, "", title, message);
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param ccEmail CC recipient. Can be empty if there is no CC recipient
     * @param title title of the message
     * @param message message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtps.auth", "true");

        /*
        If set to false, the QUIT command is sent and the connection is immediately closed. If set 
        to true (the default), causes the transport to wait for the response to the QUIT command.

        ref :   http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
                http://forum.java.sun.com/thread.jspa?threadID=5205249
                smtpsend.java - demo program from javamail
        */
        props.put("mail.smtps.quitwait", "false");

        Session session = Session.getInstance(props, null);

        // -- Create a new message --
        final MimeMessage msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username + "@gmail.com"));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

        if (ccEmail.length() > 0) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
        }

        msg.setSubject(title);
        msg.setText(message, "utf-8");
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

        t.connect("smtp.gmail.com", username, password);
        t.sendMessage(msg, msg.getAllRecipients());      
        t.close();
    }
}
Community
  • 1
  • 1
syb0rg
  • 8,057
  • 9
  • 41
  • 81
  • I have an error in the import line (javax.mail doesn't exist) – user2284478 Apr 15 '13 at 23:52
  • You need to download the [JavaMail API](http://www.oracle.com/technetwork/java/javamail/index.html), and put the relevant jar files in your classpath. – syb0rg Apr 15 '13 at 23:57
0

Here you can find sample java class written for sending emails using Google account. Please follow following link

It uses the following properties

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");
Lasa
  • 5
  • 2