Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import javax.mail.Folder;
- import javax.mail.Message;
- import javax.mail.Message.RecipientType;
- import javax.mail.MessagingException;
- import javax.mail.Session;
- import javax.mail.Store;
- import javax.mail.Transport;
- import javax.mail.internet.AddressException;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import javax.swing.JOptionPane;
- public class GmailClient {
- private String userName;
- private String password;
- private String receivingHost;
- public void setAccountDetails(String userName,String password){
- this.userName=userName;//sender's email can also use as User Name
- this.password=password;
- }
- public void readGmail(){
- /*this will print subject of all messages in the inbox of sender@gmail.com*/
- this.receivingHost="imap.gmail.com";//for imap protocol
- Properties props2=System.getProperties();
- props2.setProperty("mail.store.protocol", "imaps");
- // I used imaps protocol here
- Session session2=Session.getDefaultInstance(props2, null);
- try {
- Store store=session2.getStore("imaps");
- store.connect(this.receivingHost,this.userName, this.password);
- Folder folder=store.getFolder("INBOX");//get inbox
- folder.open(Folder.READ_ONLY);//open folder only to read
- Message message[]=folder.getMessages();
- for(int i=0;i<message.length;i++){
- //print subjects of all mails in the inbox
- System.out.println(message[i].getSubject());
- //anything else you want
- }
- //close connections
- folder.close(true);
- store.close();
- } catch (Exception e) {
- System.out.println(e.toString());
- }
- }
- public static void main(String[] args) {
- String mailFrom=new String("sender@gmail.com");
- //Sender must be a Gmail Account holder
- String mailTo=new String("receiver@gmail.com");
- //but here you can send to any type of mail account
- String senderPassword=new String("1234");
- String senderUserName=new String("sender");
- //Mention your email subject and content
- String mailSubject=new String("Testing Mail");
- String mailText=new String("Have an Nice Day ...........!!!");
- //Create a GmailClient object
- GmailClient newGmailClient=new GmailClient();
- //Setting up account details
- newGmailClient.setAccountDetails(senderUserName, senderPassword);
- //Send mail
- newGmailClient.sendGmail(mailFrom, mailTo, mailSubject, mailText);
- //Receive mails
- newGmailClient.readGmail();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement