From a Java application we can send an email to any recipient on any domain e.g. gmail, yahoomail, etc. The only thing we needed is a valid SMTP . We can also set the validation of the sender in the application during session initialization, since it isdisabled by default. If a user is sending an email within local network, the sender ID is not required, but to send across over the network, a sender Id must be included in the message header.
Below is an example which shows how to send mail using Java
package com.demo.mail;
/**
*Mail API is provided by the JAVA in
*
*/
import javax.mail.*;
import javax.mail.internet.*;
/**
*Method SendMail for sending mail form one location to another
*
*/
public class SendMail
{
public void postMail( String recipients, String subject, String message , String from) throws MessagingException
{
/**
*Properties Of the Mail Header
*
*/
Properties props = new Properties();
props.put("mail.smtp.port", "465");
props.put("mail.smtp.host", "192.168.10.1");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.socketFactory.port", "25");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
/**
*Session and Authentication Of the Message, by default
* Authentication is disabled
*/
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("username","password");
}
});
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress addressTo = new InternetAddress(recipients);
msg.setRecipient(Message.RecipientType.TO, addressTo);
/**
*Message can have multiple parts and also can have attachments
*
*/
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
public static void main(String s[])
{
SendMail mail=new SendMail();
try
{
mail.postMail("recipientsmailID","subject","JavaMail hello world example","SendersmailID");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}