The following code will assist in sending emails from a given host using smtp.
It also has methods for reading emails from external mail servers.
This is a tested code and simply copy paste of the code will run without further configuration.
package test;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessageRemovedException;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.event.FolderEvent;
import javax.mail.event.FolderListener;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.pop3.POP3Folder;
public class TestMail {
/**
* Description:
* TestMail
* @param args
* void
* Author:Ramesh Raj Baral
* @throws MessagingException
* @throws MessagingException
* @throws IOException
* @since Jun 2, 2010
*/
private static String host="hostName";
public static void main(String[] args) throws MessagingException, IOException {
// TODO Auto-generated method stub
sendEmail();
readEmail();
//readGmail();
}
/**
this method reads the emails from the inbox folder only of any pop server
*/
public static void readEmail() throws MessagingException, IOException{
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.transport.protocol", "smtp");
String password="password";
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("pop3s");//pop3
store.connect(host,"userName", password);
Folder folder = store.getFolder("inbox");//only inbox is supported by pop3
folder.open(Folder.READ_WRITE);
System.out.println("no of msg:"+folder.getUnreadMessageCount());
Message[] message = folder.getMessages();
// Display message in the descending order of received date.
for (int i = message.length-1; i >0; i--) {
try{
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
//System.out.print("Message : ");
//this part checks the unique id (UID) of the message which can be useful to decide //if the message is new or old
if (folder instanceof POP3Folder) {
POP3Folder pf =
(POP3Folder)folder;
String uid = pf.getUID(message[i]);
if (uid != null)
System.out.println("UID is:"+uid);
}
InputStream stream = message[i].getInputStream();
System.out.println("*************************************");
while (stream.available() != 0) {
//print the content of mail
System.out.print((char) stream.read());
}
System.out.println("**************************************");
}catch(MessageRemovedException mex){
System.out.println("message removed exception ");
}
}
}
/**
this method sends email
*/
public static void sendEmail() throws MessagingException, UnsupportedEncodingException{
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.transport.protocol", "smtp");
InternetAddress[] bccFilteredList = new InternetAddress[1];
bccFilteredList[0]=new InternetAddress("emailadderess@domain.com".toString(),"any name");
InternetAddress[] toFilteredList = new InternetAddress[1];
toFilteredList[0]=new InternetAddress("emailadderess@domain.com".toString(),"");
Session session = Session.getDefaultInstance(props, null);
//session.setDebug(true);//if uncommented displays all the debug info
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("fromemail@domain.com","username"));
msg.setRecipients(Message.RecipientType.TO, toFilteredList);
msg.setRecipients(Message.RecipientType.BCC,bccFilteredList);
msg.setSubject("Test msg!");
msg.setHeader("Content-Type", "text/html");
String body="Another Test msg";
msg.setText(body);
Transport.send(msg);
System.out.println("mail sent");
}
/**
this method reads the mails from gmail server of a given account
*/
public static void readGmail() throws MessagingException, IOException{
String host = "pop.gmail.com";
String user = "emailaddress@gmail.com";
String password = "password";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
System.out.println("new emails:"+folder.getNewMessageCount());;
Message[] message = folder.getMessages();
// Display message.
for (int i = message.length-1; i >0; i--) {
try{
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
//System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
//uncomment the following loop if you want to print the mail body
/* while (stream.available() != 0) {
//System.out.print((char) stream.read());
}*/
}catch(MessageRemovedException mex){
System.out.println("message removed exception ");
}
}
folder.close(true);
store.close();
}
}
Cheers,
Ramesh Baral.
No comments:
Post a Comment