import java.util.Properties;
import java.util.ResourceBundle;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Mail
{
/**
The SMTP Server to send the emails and the user name and password to
authenticate with the server. All these are read from the mail.properties file.
*/
public static String smtpServer
;
public static String userName
;
public static String password
;
static
{
smtpServer = bundle.getString("server");
userName = bundle.getString("user");
password = bundle.getString("password");
}
/**
*
* @param from
* @param to Cannot be Null
* @param subject Cannot be Null
* @param mailText
*/
{
if((to == null) && (subject == null))
return false;
if(mailText == null)
mailText = "";
if(from == null)
from = userName;
try {
props.put( "mail.smtp.host", smtpServer ) ;
//SMTP server authentication is set to false, by default. Setting it to true as shown below
props.put( "mail.smtp.auth", "true" ) ;
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
//Setting the 'from', 'to', 'cc' addresses and the 'subject'
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
//Making the mail body as inline and of html type
MimeMultipart mp = new MimeMultipart();
MimeBodyPart text = new MimeBodyPart();
text.setDisposition(Part.INLINE);
text.setContent(mailText, "text/html");
mp.addBodyPart(text);
message.setContent(mp);
//SMTP authentication
Transport transport = session.getTransport ("smtp") ;
transport.connect (smtpServer, userName, password) ;
message.saveChanges();
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return true;
System.
err.
println("Email could not be sent due to error: "+e
);
e.printStackTrace();
throw e;
}
}
public static void main
(String[] args
)
{
Mail mail = new Mail();
try {
mail.sendEmail(null,"[[email id]]","test","I am testing.");
ex.printStackTrace();
}
}
}