New Java mail API

hi!
i have downlowded Java mail API from sun site.how to proceed now.I have already installed JDK on my machine.

Read the information that comes with it.
Put mail.jar in your classpath.
Put the other jar file in your classpath, too, the one that the information says that you also have to download.
Start writing programs.

Similar Messages

  • New java mail api query?

    hello friends
    well i would like to know in new javamail api version 1.4.1 is it possible to read only unread messages from the e-mail account.
    in the earlier version 1.4 m not able to extract unread mails(only) from the e-mail account .

    Nothing has changed in 1.4.1 for this; it should work in 1.4 and 1.4.1.
    I'm not sure what you mean by "not able to". Does that mean you can't figure
    out how to do it? Or does that mean you did the right thing, but it's not working
    with your server?

  • Java mail api - sending mails to gmail account

    Hello
    I am using java mail api to send mails.when i send mails to gmail from ids which are not in gmail friends list, most of the mails are going to spam.Ofcourse, some of them go to inbox.I tried in lot of ways to analyse the problem.But nothing could help. Can anyone plzz tell me how to avoid mails going to spam in gmail, using java mail api?
    Thank you in advance,
    Regards,
    Aradhana
    Message was edited by:
    Aradhana

    am using the below code.
    Properties props = System.getProperties();
    //          Setup mail server
              props.put("mail.smtp.host", smtpHost);
              props.put("mail.smtp.port","25");
              props.put("mail.smtp.auth", isAuth);
         Authenticator auth = new UserAuthenticator();
    //          Get session
              Session s = Session.getDefaultInstance(props,auth);
    //          Define message
              Message m = new MimeMessage(s);
    //          setting message attributes
              try {
                   m.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
                   InternetAddress f_addr=new InternetAddress(from);
                   f_addr.setPersonal(personalName);
                   m.setFrom(f_addr);               
                   m.setSubject(subject);
                   m.setSentDate(new Date());
                   m.setContent(msg,"text/plain");
                   m.saveChanges();
    //               send message
                   Transport.send(m);
    Message was edited by:
    Aradhana

  • Save Attachment from exchange server 2010 from oracle using java mail API

    Hello,
    I want to read email from microsoft exchangeserver 2010 and save attachement into a folder.I created an Java program to import attachments from a exchange server mailbox using "POP3S".It works fine when run as a java application.But when i put this inside Oracle11g R2 using load java and while executing from a procedure it gives an error at parsing message into Multipart
    Error at line : Multipart mp = (Multipart)m.getContent();
    Error:
    Content-Type: multipart/mixed;
    boundary="_002_A0C2E09A..................................."
    java.lang.ClassCastException
    at mailPop3.checkmail(mailPop3:71)
    My Java Class is as follows,
    import java.io.*;
    import java.util.Properties;
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.Date;
    The function i used to check for attachments is given below.
    public static boolean hasAttachments(Message m) throws java.io.IOException, MessagingException
    Boolean hasAttachments = false;
    try
    // if it is a plain/html text - no attachements
    if (m.isMimeType("text/*"))
    return hasAttachments;
    else if (m.isMimeType("multipart/alternative"))
    return hasAttachments;
    else if (m.isMimeType("multipart/*"))
    Multipart mp = (Multipart)m.getContent();
    if (mp.getCount() > 1)
    hasAttachments = true;
    return hasAttachments;
    catch (Exception e) {
    e.printStackTrace();
    } finally {
    return hasAttachments;
    My Java Details as follows
    java Version :1.5.0_10
    java.vm.specification.version:1.0
    java.vm.version :1.5.0_01
    java.specification.version:1.5
    java.class.version:48.0
    Java mail API:javamail-1.4.4
    Used Jars:mail.jar
    Could someone explain why I am getting this error? What can I do to resolve this error?
    Is any other Jar need other than mail.jar?
    Any help would be much appreciated.
    Regards,
    Nisanth

    Hai EJP,
    Thanks for your reply,
    My full java class as follows,
    import java.util.Properties;
    import javax.mail.Authenticator;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Store;
    import javax.mail.Part;
    import javax.mail.Multipart;
    import javax.mail.internet.MimeMultipart;
    import javax.mail.internet.MimeMessage;
    public class Newmail
    public Newmail()
    super();
    public static int mailPOP3(String phost,
    String pusername,
    String ppassword)
    Folder inbox =null;
    Store store =null;
    int result = 1;
    try
    String host=phost;
    final String username=pusername;
    final String password=ppassword;
    System.out.println("Authenticator");
    Authenticator auth=new Authenticator()
    protected PasswordAuthentication getPasswordAuthentication()
    return new PasswordAuthentication(username, password);
    System.out.println("Certificate");
    String filename="D:\\Certi\\jssecacerts";
    String password2 = "changeit";
    System.setProperty("javax.net.ssl.trustStore",filename);
    System.setProperty("javax.net.ssl.trustStorePassword",password2);
    Properties props = System.getProperties();
    System.out.println("host-----"+props);
    props.setProperty("mail.pop3s.port", "993");
    props.setProperty("mail.pop3s.starttls.enable","true");
    props.setProperty("mail.pop3s.ssl.trust", "*");
    Session session = Session.getInstance(props,auth);
    session.setDebug(true);
    store = session.getStore("pop3s");
    System.out.println("store------"+store);
    store.connect(host,username,password);
    System.out.println("Connected...");
    inbox = store.getDefaultFolder().getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Message[] msgs = inbox.getMessages();
    System.out.println("msgs.length-----"+msgs.length);
    result = 0;
    int no_of_messages = msgs.length;
    for ( int i=0; i < no_of_messages; i++)
    System.out.println("msgs.count-----"+i);
    System.out.println("Attachment....>"+msgs.getContentType());
    Multipart mp = (Multipart)msgs[i].getContent();
    System.out.println("Casting Success" + mp.getContentType());
    catch(Exception e)
    e.printStackTrace();
    finally
    try
    if(inbox!=null)
    inbox.close(false);
    if(store!=null)
    store.close();
    return result;
    catch(Exception e)
    e.printStackTrace();
    return result;
    Please check it
    Regards,
    Nisanth

  • Issue with JAVA Mail API

    Hi
    We have a requirement to create a custom e mail. For the same I am trying to use Java Mail API.I am facing an issue with the following code:
    session session1 = session.getInstance(properties, null);
    System gives an error Sourced file: inline evaluation of: ``Properties props = new Properties(); session session1 = session.getInstance(prop . . . '' : Typed variable declaration : Class: session not found in namespace
    Is there some specific API i need to import for session class. Kindly suggest.
    Regards
    Shobha

    Hi Shobha,
    I was also facing the same issue from last couple of weeks and just now i have achieved the working functionality.
    Please find below working code and replace values as per your serveru2019s configuration.
    import com.sap.odp.api.util.*;
    import java.util.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    import java.io.File;
    import java.net.*;
    // SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
    String to =<email address>;
    String from =<email address>;
    // SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
    String host = <smtp host name>;
    String user = <smtp user name>;
    // Create properties, get Session
    // Properties props = new Properties();
    Properties props = System.getProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", host);
    props.put("mail.debug", "false");
    props.put("mail.smtp.auth", "false");
    props.put("mail.user",user);
    props.put("mail.from",from);
    Session d_session = Session.getInstance(props,null);//Authenticator object need to be set
    Message msg = new MimeMessage(d_session);
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = {new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject("Test E-Mail through Java");
    msg.setSentDate(new Date());
    msg.setText("This is a test of sending a " +
    "plain text e-mail through Java.\n" +
    "Here is line 2.");
    Transport.send(msg);
    Deepak!!!

  • Problem in sending messages using java mail api

    Hi All,
    I have a problem in sending messages via java mail api.
    MimeMessage message = new MimeMessage(session);
    String bodyContent = "ñSunJava";
    message.setText (bodyContent,"utf-8");using the above code its not possible for me to send the attachment. if i am using the below code means special characters like ñ gets removed or changed into some other characters.
    MimeBodyPart messagePart = new MimeBodyPart();
                messagePart.setText(bodyText);
                // Set the email attachment file
                MimeBodyPart attachmentPart = new MimeBodyPart();
                FileDataSource fileDataSource = new FileDataSource("C:/sunjava.txt") {
                    public String getContentType() {
                        return "application/octet-stream";
                attachmentPart.setDataHandler(new DataHandler(fileDataSource));
                attachmentPart.setFileName(filename);
                Multipart multipart = new MimeMultipart();
                multipart.addBodyPart(messagePart);
                multipart.addBodyPart(attachmentPart);
                message.setContent(multipart);
                Transport.send(message);is there any way to send the file attachment with the body message without using MultiPart java class.

    Taken pretty much straight out of the Javamail examples the following works for me (mail read using Thunderbird)        // Define message
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            // Set the 'to' address
            for (int i = 0; i < to.length; i++)
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    // Set the 'cc' address
    for (int i = 0; i < cc.length; i++)
    message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
    // Set the 'bcc' address
    for (int i = 0; i < bcc.length; i++)
    message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
    message.setSubject("JavaMail With Attachment");
    // Create the message part
    BodyPart messageBodyPart = new MimeBodyPart();
    // Fill the message
    messageBodyPart.setText("Here's the file ñSunJava");
    // Create a Multipart
    Multipart multipart = new MimeMultipart();
    // Add part one
    multipart.addBodyPart(messageBodyPart);
    // Part two is attachment
    for (int count = 0; count < 5; count++)
    String filename = "hello" + count + ".txt";
    String fileContent = " ñSunJava - Now is the time for all good men to come to the aid of the party " + count + " \n";
    // Create another body part
    BodyPart attachementBodyPart = new MimeBodyPart();
    // Get the attachment
    DataSource source = new StringDataSource(fileContent, filename);
    // Set the data handler to this attachment
    attachementBodyPart.setDataHandler(new DataHandler(source));
    // Set the filename
    attachementBodyPart.setFileName(filename);
    // Add this part
    multipart.addBodyPart(attachementBodyPart);
    // Put parts in message
    message.setContent(multipart);
    // Send the message
    Transport.send(message);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Using Java Mail API from Tomcat

    Hello,
    Purely as an academic exercise I have written a JSP page which, upon being requested from the client's browser, should send me a default email using Java Mail Api.
    here is the code :
    import java.util.*;
    import java.io.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    public class TestMail {
        static String msgText1 = "success this time 12";
        static String msgText2 = "This is the text in the message attachment.";
        public String sendIt() {
            String to = "<my email";
            String from = "<anything>";
            String host = "<my ip address of smtp server>";
            boolean debug = false;
            Properties props = new Properties();
            props.put("mail.smtp.host", host);
            Session session = Session.getInstance(props, null);
    .....The code works fine as a stand alone app but when called from JSP page it hangs on the Session.getInstance line. I can only guess that this might be a security issue with the container not allowing access to the smtp server ?
    Can anyone give me a clue ???

    Your Tomcat log files should spell out the problem for you.
    My Tomcat installation does not come with the Java Mail API. I had to add the mail and activation jar files to the server/common.lib directory (or the server's shared/lib or the WEB-INF/lib of your application.)
    HTH.

  • Problem in retrieving email using java mail api

    hi,
    In my project,i am retrieving mails from a particular email id.
    I am able to retrieve the latest mails and save it in a folder in my system.
    The problem is whenever i run the program eventhough the most recently received mail in inbox is retrieved and saved,again it is retrieving the same one and saving it in the same folder(not repeating).
    I tried to check the newmessages in the inbox using the folder.hasNewMessage() method in java mail api,but the method is returning false only regardless new mail is there in inbox or not.
    I want to read the unread messages only.Dont want to retrieve the already read mails.
    I got the mail retrieving code from the below site.(sorry not posting the code because it is so long and having 4 classes)
    http://www.builderau.com.au/program/java/soa/Getting_the_mail_in_receiving_in_JavaMail/0,39024620,39228060,00.htm
    Can anyone tell me how to read unread mails in the inbox?
    Thanks a lot

    hi parvathi
    i think your mail program is receving mails using imap
    the imap is only receve the mail from server but the pop is deleting the mails after receving
    use the following sample code
    package com.sfrc.mail.pop;
    import javax.mail.*;
    import javax.mail.internet.*;
    import com.sun.mail.handlers.message_rfc822;
    import java.util.*;
    import java.io.*;
    * Owner: SFRC IT Solutions Pvt Ltd
    * Author:Arunkumar Subramaniam
    * Date :12-06-2006
    * File Name: AttachRecive.java
    public class AttachRecive
    public static void main(String args[])
    try
    String popServer="192.168.1.1";
    String popUser="pl";
    String popPassword="password";
    // Create empty properties
    Properties props = new Properties();
    // Get session
    Session session = Session.getDefaultInstance(props, null);
    // Get the store
    Store store = session.getStore("pop3");
    store.connect(popServer, popUser, popPassword);
    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);
    // Get directory
    Message message =folder.getMessages();
    Multipart mp = (Multipart)message.getContent();
    for (int i=0, n=mp.getCount(); i<n; i++) {
    Part part = mp.getBodyPart(i);
    String disposition = part.getDisposition();
    // Close connection
    folder.close(false);
    store.close();
    catch (Exception ex)
    System.out.println("Usage: "
    +" popServer popUser popPassword");
    System.exit(0);
    Regards
    Arunkumar Subramaniam
    SFRC IT Solutions Pvt Ltd
    Chennai

  • Java.lang.UnsupportedClassVersionError while using java mail api

    Hi Everybody ,
    I am new comer to this forum , and would like to be an active member.
    I am getting this error while trying to use the java mail api to send an email using smtp.
    The error is as follows :
    Exception in thread "main" java.lang.UnsupportedClassVersionError: javax/mail/Message (Unsupported major.minor version 48.0)
    Can Anyone please tell where I am wrong.
    I am using the following code
    ==============================================================
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.abc.com");
    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);
    // create a message
    Message msg = new MimeMessage(session);
    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++)
    addressTo[i] = new InternetAddress(recipients);
    msg.setRecipients(Message.RecipientType.TO, addressTo);
    // Optional : You can also set your custom headers in the Email if you Want
    msg.addHeader("MyHeaderName", "myHeaderValue");
    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
    ==============================================================

    Hi Philip ,
    Thanks for the prompt reply , I had installed oracle client services which overid my jdk1.4 installation with jdk1.3 and hence the error. I changed my classpath settings to point to jdk1.4 and it owrked properly.
    Thanks once again.
    regards,
    Rupesh Rajan

  • Java mail api: SendFailedException when trying to send Mail via SMTP

    Hello,
    I'm trying to send a mail via java mail api using a server that requires smtp authentication.
    I'm currently using the following code:
    protocol = "smtp";
    host = "auth.smtp.profimailer.de";
    port = 25;
    String from="[email protected]";
    String to="[email protected]";
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", "true");
    Authenticator auth = new PopupAuthenticator();
    session=Session.getInstance(props,auth);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from,"[email protected]"));
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to,"ToName"));
    message.setSubject("Hello JavaMail");
    message.setText("Welcome to JavaMail");
    Transport.send(message);
    static class PopupAuthenticator extends Authenticator {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("e12345676", "mypass");
    }When trying to run this code, I get the following exception:
    D:\eclipse30RC1\workspace\ClassifyIt\bin>java -cp .;../lib/javamail.jar de.jwannenmacher.classify.TestMail > test.txt
    javax.mail.SendFailedException: Send failed;
    nested exception is:
    javax.mail.SendFailedException: Sender "[email protected]" <jens
    @jens-wannenmacher.de> was rejected: 501
    at javax.mail.Transport.doSend(Transport.java:223)
    at javax.mail.Transport.send(Transport.java:92)
    at de.jwannenmacher.mail.pop3client.POP3Client.getAllNewMessages(POP3Cli
    ent.java:176)
    at de.jwannenmacher.classify.TestMail.main(TestMail.java:22)
    Any suggestions on this?
    Thanks and best regards,
    Jens

    Hi,
    yes smtp is a standard and I think you could use this with almost every smtp server.
    If your smtp server doesn't require authentication you can access it without an authenticator
    I think...
    Best regards,
    Jens

  • Complete working code for Gmail POP3 & SMTP with SSL - Java mail API

    Finally, your code-hunt has come to an end!!!!
    I am presenting you the complete solution (with code) to send and retrieve you mails to & from GMAIL using SMTP and POP3 with SSL & Authenticaion enabled. [Even starters & newbies like me, can easy try, test & understand - But first download & add JAR's of Java Mail API & Java Activation Framework to Netbeans Library Manager]
    Download Java Mail API here
    http://java.sun.com/products/javamail/
    Read Java Mail FAQ's here
    http://java.sun.com/products/javamail/FAQ.html
    Download Java Activation Framework [JAF]
    http://java.sun.com/products/javabeans/jaf/downloads/index.html
    Also, The POP program retrieves the mail sent with SMTP program :) [MOST IMPORTANT & LARGELY IN DEMAND]okey.. first things first... all of your thanks goes to the following and not a s@!te to me :)
    hail Java !!
    hail Java mail API !!
    hail Java forums !!
    hail Java-tips.org !!
    hail Netbeans !!
    Thanks to all coders who helped me by getting the code to work in one piece.
    special thanks to "bshannon" - The dude who runs this forum from 97!!I am just as happy as you will be when you execute the below code!! [my 13 hours of tweaking & code hunting has paid off!!]
    Now here it is...I only present you the complete solution!!
    START OF PROGRAM 1
    SENDING A MAIL FROM GMAIL ACCOUNT USING SMTP [STARTTLS (SSL)] PROTOCOL OF JAVA MAIL APINote on Program 1:
    1. In the code below replace USERNAME & PASSWORD with your respective GMAIL account username and its corresponding password!
    2. Use the code to make your Gmail client [jsp/servlets whatever]
    //Mail.java - smtp sending starttls (ssl) authentication enabled
    //1.Open a new Java class in netbeans (default package of the project) and name it as "Mail.java"
    //2.Copy paste the entire code below and save it.
    //3.Right click on the file name in the left side panel and click "compile" then click "Run"
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    public class Main
        String  d_email = "[email protected]",
                d_password = "PASSWORD",
                d_host = "smtp.gmail.com",
                d_port  = "465",
                m_to = "[email protected]",
                m_subject = "Testing",
                m_text = "Hey, this is the testing email.";
        public Main()
            Properties props = new Properties();
            props.put("mail.smtp.user", d_email);
            props.put("mail.smtp.host", d_host);
            props.put("mail.smtp.port", d_port);
            props.put("mail.smtp.starttls.enable","true");
            props.put("mail.smtp.auth", "true");
            //props.put("mail.smtp.debug", "true");
            props.put("mail.smtp.socketFactory.port", d_port);
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
            SecurityManager security = System.getSecurityManager();
            try
                Authenticator auth = new SMTPAuthenticator();
                Session session = Session.getInstance(props, auth);
                //session.setDebug(true);
                MimeMessage msg = new MimeMessage(session);
                msg.setText(m_text);
                msg.setSubject(m_subject);
                msg.setFrom(new InternetAddress(d_email));
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
                Transport.send(msg);
            catch (Exception mex)
                mex.printStackTrace();
        public static void main(String[] args)
            Main blah = new Main();
        private class SMTPAuthenticator extends javax.mail.Authenticator
            public PasswordAuthentication getPasswordAuthentication()
                return new PasswordAuthentication(d_email, d_password);
    END OF PROGRAM 1-----
    START OF PROGRAM 2
    RETRIVE ALL THE MAILS FROM GMAIL INBOX USING Post Office Protocol POP3 [SSL] PROTOCOL OF JAVA MAIL APINote:
    1.Log into your gmail account via webmail [http://mail.google.com/]
    2.Click on "settings" and select "Mail Forwarding & POP3/IMAP"
    3.Select "enable POP for all mail" and "save changes"
    4.In the code below replace USERNAME & PASSWORD with your respective GMAIL account username and its corresponding password!
    PROGRAM 2 - PART 1 - Main.java
    //1.Open a new Java class file in the default package
    //2.Copy paste the below code and rename it to Mail.java
    //3.Compile and execute this code.
    public class Main {
        /** Creates a new instance of Main */
        public Main() {
         * @param args the command line arguments
        public static void main(String[] args) {
            try {
                GmailUtilities gmail = new GmailUtilities();
                gmail.setUserPass("[email protected]", "PASSWORD");
                gmail.connect();
                gmail.openFolder("INBOX");
                int totalMessages = gmail.getMessageCount();
                int newMessages = gmail.getNewMessageCount();
                System.out.println("Total messages = " + totalMessages);
                System.out.println("New messages = " + newMessages);
                System.out.println("-------------------------------");
    //Uncomment the below line to print the body of the message. Remember it will eat-up your bandwidth if you have 100's of messages.            //gmail.printAllMessageEnvelopes();
                gmail.printAllMessages();
            } catch(Exception e) {
                e.printStackTrace();
                System.exit(-1);
    END OF PART 1
    PROGRAM 2 - PART 2 - GmailUtilities.java
    //1.Open a new Java class in the project (default package)
    //2.Copy paste the below code
    //3.Compile - Don't execute this[Run]
    import com.sun.mail.pop3.POP3SSLStore;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Address;
    import javax.mail.FetchProfile;
    import javax.mail.Flags;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.Part;
    import javax.mail.Session;
    import javax.mail.Store;
    import javax.mail.URLName;
    import javax.mail.internet.ContentType;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.ParseException;
    public class GmailUtilities {
        private Session session = null;
        private Store store = null;
        private String username, password;
        private Folder folder;
        public GmailUtilities() {
        public void setUserPass(String username, String password) {
            this.username = username;
            this.password = password;
        public void connect() throws Exception {
            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            Properties pop3Props = new Properties();
            pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
            pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
            pop3Props.setProperty("mail.pop3.port",  "995");
            pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
            URLName url = new URLName("pop3", "pop.gmail.com", 995, "",
                    username, password);
            session = Session.getInstance(pop3Props, null);
            store = new POP3SSLStore(session, url);
            store.connect();
        public void openFolder(String folderName) throws Exception {
            // Open the Folder
            folder = store.getDefaultFolder();
            folder = folder.getFolder(folderName);
            if (folder == null) {
                throw new Exception("Invalid folder");
            // try to open read/write and if that fails try read-only
            try {
                folder.open(Folder.READ_WRITE);
            } catch (MessagingException ex) {
                folder.open(Folder.READ_ONLY);
        public void closeFolder() throws Exception {
            folder.close(false);
        public int getMessageCount() throws Exception {
            return folder.getMessageCount();
        public int getNewMessageCount() throws Exception {
            return folder.getNewMessageCount();
        public void disconnect() throws Exception {
            store.close();
        public void printMessage(int messageNo) throws Exception {
            System.out.println("Getting message number: " + messageNo);
            Message m = null;
            try {
                m = folder.getMessage(messageNo);
                dumpPart(m);
            } catch (IndexOutOfBoundsException iex) {
                System.out.println("Message number out of range");
        public void printAllMessageEnvelopes() throws Exception {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();
            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);       
            folder.fetch(msgs, fp);
            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs);
    public void printAllMessages() throws Exception {
    // Attributes & Flags for all messages ..
    Message[] msgs = folder.getMessages();
    // Use a suitable FetchProfile
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);
    folder.fetch(msgs, fp);
    for (int i = 0; i < msgs.length; i++) {
    System.out.println("--------------------------");
    System.out.println("MESSAGE #" + (i + 1) + ":");
    dumpPart(msgs[i]);
    public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
    dumpEnvelope((Message)p);
    String ct = p.getContentType();
    try {
    pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
    pr("BAD CONTENT-TYPE: " + ct);
    * Using isMimeType to determine the content type avoids
    * fetching the actual content data until we need it.
    if (p.isMimeType("text/plain")) {
    pr("This is plain text");
    pr("---------------------------");
    System.out.println((String)p.getContent());
    } else {
    // just a separator
    pr("---------------------------");
    public static void dumpEnvelope(Message m) throws Exception {       
    pr(" ");
    Address[] a;
    // FROM
    if ((a = m.getFrom()) != null) {
    for (int j = 0; j < a.length; j++)
    pr("FROM: " + a[j].toString());
    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
    for (int j = 0; j < a.length; j++) {
    pr("TO: " + a[j].toString());
    // SUBJECT
    pr("SUBJECT: " + m.getSubject());
    // DATE
    Date d = m.getSentDate();
    pr("SendDate: " +
    (d != null ? d.toString() : "UNKNOWN"));
    static String indentStr = " ";
    static int level = 0;
    * Print a, possibly indented, string.
    public static void pr(String s) {
    System.out.print(indentStr.substring(0, level * 2));
    System.out.println(s);
    }END OF PART 2
    END OF PROGRAM 2
    P.S: CHECKING !!
    STEP 1.
    First compile and execute the PROGRAM 1 with your USERNAME & PASSWORD. This will send a mail to your own account.
    STEP 2.
    Now compile both PART 1 & PART 2 of PROGRAM 2. Then, execute PART 1 - Main.java. This will retrive the mail sent in step 1. njoy! :)
    In future, I hope this is added to the demo programs of the Java Mail API download package.
    This is for 3 main reasons...
    1. To prevent a lot of silly questions being posted on this forum [like the ones I did :(].
    2. To give the first time Java Mail user with a real time working example without code modification [code has to use command line args like the demo programs - for instant results].
    3. Also, this is what google has to say..
    "The Gmail Team is committed to making sure you always can access your mail. That's why we're offering POP access and auto-forwarding. Both features are free for all Gmail users and we have no plans to charge for them in the future."
    http://mail.google.com/support/bin/answer.py?answer=13295
    I guess bshannon & Java Mail team is hearing this....
    Again, Hurray and thanks for helping me make it!! cheers & no more frowned faces!!
    (: (: (: (: (: GO JCODERS GO!! :) :) :) :) :)
    codeace
    -----                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

    Thanks for the reply,
    I did checked by enabling session debuging and also checked pop settings it's enabled for all
    mails, I tried deleting some very old messages and now the message count is changed to 310.
    This may be the problem with gmail.
    Bellow is the output i got,
    DEBUG: setDebug: JavaMail version 1.4ea
    DEBUG: getProvider() returning javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]
    DEBUG POP3: connecting to host "pop.gmail.com", port 995, isSSL false
    S: +OK Gpop ready for requests from 121.243.255.240 n22pf5432603pof.2
    C: USER [email protected]
    S: +OK send PASS
    C: PASS my_password
    S: +OK Welcome.
    C: STAT
    S: +OK 310 26900234
    Custom output: messageCount : 310
    C: QUIT
    S: +OK Farewell.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problem using Java Mail API with WLS 7.0

    Hi All,
    I am trying to use the Java Mail API provided by WLS 7.0. I have made the
    settings metioned in the WLS 7.0 docs. However when I try to run the program I
    am getting the following error:
    javax.naming.NoInitialContextException: Need to specify class name in environment
    or system property, or as an applet parameter, or in an application resource file:
    java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:6
    46)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:246
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.jav
    a:283)
    at javax.naming.InitialContext.lookup(InitialContext.java:350)
    The code that I have written is as follows
    import java.util.*;
    import javax.activation.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.naming.*;
    import java.io.*;
    import java.net.InetAddress;
    import java.util.Properties;
    import java.util.Date;
    public class MailTo {
         public static void main(String args[])
              try
                   //Context ic = getInitialContext();
                   InitialContext ic = new InitialContext();
    /* My jndi name is "testSession" */
                   Session session = (Session) ic.lookup("testSession"); /* THE PROBLEM IS SHOWN
    IN THIS LINE */
                   Properties props = new Properties();
                   props.put("mail.transport.protocol", "smtp");
                   props.put("mail.smtp.host", "XX.XX.XX.XX");
    /* For security reasons I have written the ip add in this format */
                   props.put("mail.from", "[email protected]"); /* for security reasons i have
    changed the mail address */
                   Session session2 = session.getInstance(props);
                   Message msg = new MimeMessage(session2);
                   msg.setFrom();
                   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]",
    false));
                   msg.setSubject("Test Message");
                   msg.setSentDate(new Date());
                   MimeBodyPart mbp = new MimeBodyPart();
                   mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
                   Multipart mp = new MimeMultipart();
                   mp.addBodyPart(mbp);
                   msg.setContent(mp);
                   Transport.send(msg);
              catch(Exception e)
                   e.printStackTrace();
         }//end of main
    public static Context getInitialContext()
         throws NamingException
              Properties p = new Properties();
              p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
              p.put(Context.PROVIDER_URL, "t3://localhost:7501/testWebApp");
                   p.put(Context.SECURITY_PRINCIPAL, "weblogic");
                   p.put(Context.SECURITY_CREDENTIALS, "weblogic");
              return new InitialContext(p);
    }//end of class
    Can anyone please tell me what is the problem. I thought that we cannot directly
    do
    InitialContext ic = new InitialContext();
    So I had written a method getInitialContext() as shown in the above piece of code,
    but that too did not work.
    Eagerly awaiting a response.
    Jimmy Shah

    You can use InitialContext ic = new InitialContext() only if you are using a startup class, servlet or a JSP i.e
    server side code.
    If you are using a java client you need to use Context ic = getInitialContext();
    Try this code
    import java.util.*;
    import javax.activation.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.naming.*;
    import java.io.*;
    import java.net.InetAddress;
    import java.util.Properties;
    import java.util.Date;
    public class MailTo {
    public static void main(String args[])
    try {
    Properties h = new Properties();
    h.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
    h.put(Context.PROVIDER_URL, "t3://localhost:7001");
    Context ic = new InitialContext(h);
    Session session = (Session) ic.lookup("testSession");
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", "XX.XX.XX.XX");
    props.put("mail.from", "[email protected]");
    Session session2 = session.getInstance(props);
    Message msg = new MimeMessage(session2);
    msg.setFrom();
    msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]",false));
    msg.setSubject("Test Message");
    msg.setSentDate(new Date());
    MimeBodyPart mbp = new MimeBodyPart();
    mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp);
    msg.setContent(mp);
    Transport.send(msg);
    catch(Exception e)
    e.printStackTrace();
    }//end of main
    }//end of class
    We have shipped a javamail example in the samples\server\src\examples\javamail folder.
    Jimmy Shah wrote:
    Hi All,
    I am trying to use the Java Mail API provided by WLS 7.0. I have made the
    settings metioned in the WLS 7.0 docs. However when I try to run the program I
    am getting the following error:
    javax.naming.NoInitialContextException: Need to specify class name in environment
    or system property, or as an applet parameter, or in an application resource file:
    java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:6
    46)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:246
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.jav
    a:283)
    at javax.naming.InitialContext.lookup(InitialContext.java:350)
    The code that I have written is as follows
    import java.util.*;
    import javax.activation.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.naming.*;
    import java.io.*;
    import java.net.InetAddress;
    import java.util.Properties;
    import java.util.Date;
    public class MailTo {
    public static void main(String args[])
    try
    //Context ic = getInitialContext();
    InitialContext ic = new InitialContext();
    /* My jndi name is "testSession" */
    Session session = (Session) ic.lookup("testSession"); /* THE PROBLEM IS SHOWN
    IN THIS LINE */
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", "XX.XX.XX.XX");
    /* For security reasons I have written the ip add in this format */
    props.put("mail.from", "[email protected]"); /* for security reasons i have
    changed the mail address */
    Session session2 = session.getInstance(props);
    Message msg = new MimeMessage(session2);
    msg.setFrom();
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]",
    false));
    msg.setSubject("Test Message");
    msg.setSentDate(new Date());
    MimeBodyPart mbp = new MimeBodyPart();
    mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp);
    msg.setContent(mp);
    Transport.send(msg);
    catch(Exception e)
    e.printStackTrace();
    }//end of main
    public static Context getInitialContext()
    throws NamingException
    Properties p = new Properties();
    p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
    p.put(Context.PROVIDER_URL, "t3://localhost:7501/testWebApp");
    p.put(Context.SECURITY_PRINCIPAL, "weblogic");
    p.put(Context.SECURITY_CREDENTIALS, "weblogic");
    return new InitialContext(p);
    }//end of class
    Can anyone please tell me what is the problem. I thought that we cannot directly
    do
    InitialContext ic = new InitialContext();
    So I had written a method getInitialContext() as shown in the above piece of code,
    but that too did not work.
    Eagerly awaiting a response.
    Jimmy Shah--
    Rajesh Mirchandani
    Developer Relations Engineer
    BEA Support

  • Using Java mail API from JSPDynPage

    Hi Experts,
    I am working on a Portal Assignment that requiresto sent work flow mails on the basis of error conditions.
    Can u please suggest if at all I can use Java Mail APIs from JSP page within the JSP DYN Page Framework.
    If at all Java Mail can be used could u please suugest some help docs on the same.
    Thanks for the help.
    Manab C Ghosh
    EP Consultant
    Kolkata INDIA
    +919830603327

    Hi Experts,
    Thanks for all the responses to my Mail question(mailing from JSPDynPage).
    I have found the solution.
    Here is how I have got the things: (pls note there are other solns)
    Using Java Mail APIs;
    Create a Java file in the scr.core / src.api
    MailSender.java
    * Created on Jul 21, 2005
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    package com.mailsend.test;
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    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;
    * Edited on Jul 24, 2005
    * @author Manab C Ghosh
    public class MailSender {
         public String sendMessage(){
            String msg ="Hello mail Test";
            String smtpServer ="mySMTPServer";
            String smtpSender = "senderemailaddress";
            String smtpRecipient="receipientemailaddress";
            String stBody =  msg ;
            //String stDate = new Date().toString() ;
            String stSubject = "Mail Test ";
            Send(     smtpServer,          //SMTPServer
                      smtpSender,          //Sender
                      smtpRecipient,     //Recipient
                      stSubject,          //Subject
                      stBody               //Body
                        );               //Attachments                    
         return "Mail Success";
    public static void Send(String SMTPServer,
                                  String From,
                                  String To,
                                  String Subject,
                                  String msgText1
            // Error status;
            int ErrorStatus = 0;
            // create some properties and get the default Session
            Properties props = System.getProperties();
            props.put("mail.smtp.host", SMTPServer);
            Session session = Session.getDefaultInstance(props, null);     
            try {
                 // create a message
                 MimeMessage msg = new MimeMessage(session);
                 msg.setFrom(new InternetAddress(From));
                 InternetAddress[] address = {new InternetAddress(To)};
                 msg.setRecipients(Message.RecipientType.TO, address);
                 msg.setSubject(Subject);
                 // create and fill the first message part
                 MimeBodyPart mbp1 = new MimeBodyPart();
                 mbp1.setText(msgText1);
                 // create the Multipart and its parts to it
                 Multipart mp = new MimeMultipart();
                 mp.addBodyPart(mbp1);
                 //mp.addBodyPart(mbp2);
                 // add the Multipart to the message
                 msg.setContent(mp);
                 // set the Date: header
                 msg.setSentDate(new Date());
                 // send the message
                 Transport.send(msg);
            } catch (MessagingException mex) {
    Call this file from the JSP page (which is set at JSPDynPage controller)
    one important thing-----
    Create a dir under PORTAL-INF and import the following jars-- activation.jar, mail.jar,imap.jar,smtp.jar, mailapi.jar.
    This works..
    Thanks once again to the Experts.
    happy mailing
    Manab Ghosh.
    INDIA (+919830603327)

  • How can i access gmail's smtp server using java mail api

    i m using java mail api to access gmails pop and smtp service to receive and send mail from ur gmail account. I m able to access gmails pop server using the ssl and port 995 , but i can not use its smtp server to which i m connecting using ssl on 465 port. It requires authentication code.
    if anybody can help me in this regard i m thnkful to him/her.
    thnks in advance.
    jogin desai

    Here's an example of using SSL + Authentication
    http://onesearch.sun.com/search/onesearch/index.jsp?qt=ssl+authentication&subCat=siteforumid%3Ajava43&site=dev&dftab=siteforumid%3Ajava43&chooseCat=javaall&col=developer-forums

  • Error while sending mail when using Java Mail API

    Hi Experts,
    I am trying to execute a webdynpro application which uses the Java Mail API to send emails. The exception that I get on executing the application is :
    Sending failed;  nested exception is: javax.mail.SendFailedException: Invalid Addresses;  nested exception is: javax.mail.SendFailedException: 550 5.7.1 Unable to relay for [email protected]
    Can anybody please help me sort out the issue.
    Regards
    Abdullah

    Hi,
    Usually one get this error if the SMTP server is configured not to relay mails (a security measure) or the SMTP server need the mail to be sent from a trusted IP or with proper authentication. Some SMTP servers are configured to block junk mails.
    Pls check with your  mail server administrator.
    Regards

Maybe you are looking for

  • Photo Orientation - Aperture 3 to Apple TV 2

    About a year ago I imported my iPhoto library of about 23,000 photos to Aperture 3.  The iPhoto library had some small corruptions in it and I was hoping the more robust nature of Aperture 3 would fix these, but the import made the corruption issues

  • Sudden spike in strain measurement

    Hi! I have a PXI 1062Q Chassis, 8108 controller (Windows OS), one PXI 4472 module(Slot 2) & two PXI 4331 modules(Slot 3 & Slot 5). The test scenario involves measurement from strain gauges mounted on a plate which is subject to some impact. But when

  • Importing "24p Cinema" footage from Canon AVCHD camera ?

    Hi all, I have bought a CANON HFS10 Vixia AVCHD camera, I`ve made some footage using the "24p cinema" mode. When using media browser in PPCS5 and importing it, it still indicates (like in CS4) under "properties", that the footage is "29.97 fps", as C

  • Can anyone help with PaintComponent???

    Can someone give me a bit of backgroubd on the paintComponent method in a JPanel? I am under the impression that it is called by paint(), and that paint is only called when the screen needs to be refresed. However, in my program, paintComponenet is c

  • Where are the 6-core Mac Pro at 3.33GHz in the 'store'???

    I'm trying to configure a 6-core Mac Pro at 3.33GHz with some extras but, it's nowhere to be found at the online store!... What gives?? Thanks