You can build build mail and messaging applications with the help of JavaMail API, which gives you access to a platform-independent and protocol-independent framework. You can use the JavaMail API as an optional package, but ensure to use with the Java SE platform. Java EE platform is also connected with it.
Following are some of the protocols supported in JavaMail API:
SMTP
POP
IMAP
MIME
NNTP
If you want to send email through your program, all you need to do is download the following jar file(s).
Sending mail through SMPT server
SMTP server is must to send emails.
Below are some techniques to get the SMTP server:
- Install and use any SMTP server such as Postfix server, Apache James server
- Use the SMTP server provided by the host provider for eg: free SMTP provide by JangoSMTP
OR
Use the SMTP Server provided by companies e.g. gmail, yahoo, etc.
Steps to send email
I am using JangoSMTP service which is free trail to use.
Create your account on JangoMail and you are ready to go then.
Create a java class file SendEmail, the contents of which are as follows:
package yourPackage;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
String to = "receiver@xyz.com"; // Recipient's email ID
String from = "sender@abc.com"; // Sender's email ID
final String username = "username";//change accordingly (Put your User name here)
final String password = "*******"; //change accordingly (Put your Password here)
// if sending mails through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Mail");
// Now set the actual message
message.setText("Hi there" +
"Put your message body here.");
// Send message
Transport.send(message);
System.out.println("Message Sent");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Now compile the class with the downloaded jar file(s).
and run
If you see
Message Sent in the console of your browser then the message is sent successfully.
0 Comment(s)