Lets discuss about how to send an email through a java program.
U will need to download the following files to run this program as it will be using them:
1.) mail.jar ( from javamail download)
2.) activation.jar (from javabeans activation framework (JAF) download).
Download these files and include them in your project.
it might look like this::
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail {
public static void main(String[] args) {
// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
String to = "bbc@hotmail.com";
String from = "abc@yahoo.com";
// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
String host = "smtp.yourisp.net";
//or:: String host = "192.168.22.11";
// Create properties, get Session
Properties props = new Properties();
// If using static Transport.send(),
// need to specify which host to send it to
props.put("mail.smtp.host", host);
// To see what is going on behind the scene
props.put("mail.debug", "true");
Session session = Session.getInstance(props);
try {
// Instantiate a message
Message msg = new MimeMessage(session);
//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Send E-mail through java");
msg.setSentDate(new Date());
// Set message content
msg.setText("Your loss has been registered successfully. Please save the LossID for future reference");
//Send the message
Transport.send(msg);
}
catch (MessagingException ex) {
// Prints all nested (chained) exceptions as well
ex.printStackTrace();
}
}
}//End of class
In this way the email gets queued into ur server to be sent.
Remember one thing.. see to it that the jdk u using is compatible with the mail.jar and activation.jar u going to use. For example u might not be able to use the latest mail.jar or activation.jar with the old jdk.
Thats it... Its that easy..
1 comment:
thanks for explaining it so well !!
u rock Machaaa !!
keep up the good work !!
y dont u try ur luck as a prof in VIT.. our college reallyyyy needs one :):P
Post a Comment