If you're just learning how to send a mail through Java, try the following otherwise, you need to set it to your email provider SMTP server, and this SMTP server in turn sends the mail to the appropriate location which is not the case with this code.
NOTE : The code is written in Java Servlet.
public class MailClient extends HttpServlet
{
private class SMTPAuthenticator extends Authenticator
{
private PasswordAuthentication authentication;
public SMTPAuthenticator(String login, String password)
{
authentication = new PasswordAuthentication(login, password);
}
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return authentication;
}
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
String from = "xyz.com";
String to = "abc.com";
String subject = "Your Subject.";
String message = "Message Text.";
String login = "xyz.com";
String password = "password";
Properties props = new Properties();
props.setProperty("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
Authenticator auth = new SMTPAuthenticator(login, password);
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
try
{
msg.setText(message);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
Transport.send(msg);
}
catch (MessagingException ex)
{
Logger.getLogger(MailClient.class.getName()).
log(Level.SEVERE, null, ex);
}
}
finally
{
out.close();
}
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
processRequest(request, response);
}
@Override
public String getServletInfo()
{
return "Short description";
}
}