How to use JavaMail

Hi,
I want to send an email through a servlet using the
javaMail API. I haven't used it before and have no idea on how to use it. I used the oreilly classes in the past but now I want to send attachments. Could anybody help me?
Thanks in advance,

This is a sample
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(filepath and name);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
mp.addBodyPart(mbp2);

Similar Messages

  • How to use JavaMail 1.4 with Oracle Application Server 10g (9.0.4.0.0)

    Hi all,
    I'd like to know if it's possible and how to use JavaMail 1.4 with Oracle Application Server 10g (9.0.4.0.0), Windows version.
    With the following code, I can see that the mail.jar used by the server is the one included in the jdk installation :
    // I'm testing InternetAddress.class because I want to use commons-email-1.2.jar that requires mail.jar 1.4 (or higher) and activation.jar 1.1 (or higher)
    // and I know that inside the commons-email-1.2.jar file, I need to call the InternetAddress.validate() method that throws a java.lang.NoSuchMethodError: javax.mail.internet.InternetAddress.validate()V if it is used with mail.jar 1.2.
    Class cls = javax.mail.internet.InternetAddress.class;
    java.security.ProtectionDomain pDomain = cls.getProtectionDomain();
    java.security.CodeSource cSource = pDomain.getCodeSource();
    java.net.URL location = cSource.getLocation();
    System.out.println(location.toString());
    This code returns : file:/C:/oracle/app/jdk/jre/lib/ext/mail.jar and this mail.jar file has an implementation version number: 1.2
    - I've tried to include my own mail.jar (1.4.2) and activation.jar (1.1.1) files in the war file that I deploy, but it doesn't work (the server still uses the same mail.jar 1.2)
    - I've tried to put the mail.jar (1.4.2) and activation.jar (1.1.1) files in the applib directory of my OC4J instance, but it doesn't work (the server still uses the same mail.jar 1.2)
    - I know that a patch exists : I've read the following document: How to Make Libraries such as mail.jar and activation.jar Swappable ? [ID 552432.1]
    This article talks about the Patch 6514136, but this patch only applies to : Oracle Containers for J2EE - Version: 10.1.3.3.0
    Can you please help me ?
    Thanks in advance for your answers,
    Laurent

    I strongly suggest to upgrade to AS 10.1.3 to get this.
    Think of future support of AS 9.0.4. You will get not critical patch updates anymore.
    --olaf                                                                                                                                                                                                                                                                                                               

  • How to use JavaMail to receive incomming email?

    Hello,
    I am a year 3 student and doing a final year project about web hosting.
    I want to know how to use JavaMail to receive and treat the incomming email. It means that the incoming email how to process and store the "message" in the recipient "folder" in the "store" class.
    If you have any optinions or examples or suggestion, please contact me.
    Thank you for your attention....

    First, it would be better to post questions about JavaMail in the JavaMail forum and not in the JSP forum.
    Second, the JavaMail download comes with a set of examples, including some that cover exactly what you ask.

  • How to use Javamail for accessing additional mailboxes -IMAP, Exchange 2010

    hi,
    I want to access a shared mailbox (NOT FOLDER) via Javamail API (1.4.5) using IMAP(s) with plain logon. The mailserver is a Exchange Server 2010.
    User: user1 ([email protected])
    pwd: xxxx
    shared mailbox: [email protected]
    Properties:
    mail.imaps.socketFactory.port = 993
    mail.imaps.starttls.enable = true
    mail.imaps.socketFactory.class = javax.net.ssl.SSLSocketFactory
    mail.imaps.socketFactory.fallback = false
    username = [email protected]
    password = xxxx
    I´ve managed to get access to the user1 - mailbox:
    Session session = Session.getInstance(properties, new ExchangeAuthenticator(username, password));
    session.setDebug(true);
    Store store = session.getStore("imaps");
    store.connect(imapHost, username, password);
    --> this works just fine! But now i want to access the additional mailbox by changing the login-String:
    [email protected]/shared_MB (user@domain/additional_MB)
    --> unfortunately I´m getting an "NO AUTHENTICATE" message:
    DEBUG: setDebug: JavaMail version 1.4.5
    DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc]
    DEBUG: mail.imap.fetchsize: 16384
    DEBUG: mail.imap.statuscachetimeout: 1000
    DEBUG: mail.imap.appendbuffersize: -1
    DEBUG: mail.imap.minidletime: 10
    DEBUG: trying to connect to host "host.domain.com", port 993, isSSL true
    * OK The Microsoft Exchange IMAP4 service is ready.
    A0 CAPABILITY
    * CAPABILITY IMAP4 IMAP4rev1 AUTH=NTLM AUTH=GSSAPI AUTH=PLAIN UIDPLUS CHILDREN IDLE NAMESPACE LITERAL+
    A0 OK CAPABILITY completed.
    DEBUG IMAP: AUTH: NTLM
    DEBUG IMAP: AUTH: GSSAPI
    DEBUG IMAP: AUTH: PLAIN
    DEBUG: protocolConnect login, host=host.domain.com, [email protected]/shared_MB, password=<non-null>
    DEBUG IMAP: AUTHENTICATE PLAIN command trace suppressed
    DEBUG IMAP: AUTHENTICATE PLAIN command result: A1 NO AUTHENTICATE failed.
    javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
    I was able to get access with Thunderbird and also with the Exchange OWA-Client, so I think there is something missing in my code...
    or is it just impossible to get access to a different mailbox using javamail and plain-auth?
    Thank you in advance.

    Thanks bshannon, that was a great idea!
    I haven´t found an solution yet, but I have maybe identified the real problem:
    Here is some interessting Thunderbird - Logging stuff:
    744[7161040]: try to log in
    744[7161040]: IMAP auth: server caps 0x1187235, pref 0x1006, failed 0x0, avail caps 0x1004
    744[7161040]: (GSSAPI = 0x1000000, CRAM = 0x20000, NTLM = 0x100000, MSN = 0x200000, PLAIN = 0x1000, LOGIN = 0x2, old-style IMAP login = 0x4)auth external IMAP login = 0x20000000
    744[7161040]: trying auth method 0x1000
    744[7161040]: got new password
    744[7161040]: IMAP: trying auth method 0x1000
    744[7161040]: PLAIN auth
    744[7161040]: 7082000:xmail.domain.com:NA:SendData: 2 authenticate plain
    744[7161040]: ReadNextLine [stream=7ec9e88 nb=3 needmore=0]
    744[7161040]: 7082000:xmail.domain.com:NA:CreateNewLineFromSocket: +
    744[7161040]: 7082000:xmail.domain.com:NA:SendData: Logging suppressed for this command (it probably contained authentication information)
    744[7161040]: ReadNextLine [stream=7ec9e88 nb=27 needmore=0]
    744[7161040]: 7082000:xmail.domain.com:NA:CreateNewLineFromSocket: 2 NO AUTHENTICATE failed.
    744[7161040]: authlogin failed
    744[7161040]: marking auth method 0x1000 failed
    ---> okay, so PLAIN AUTH is failing.....
    744[7161040]: IMAP auth: server caps 0x1187235, pref 0x1006, failed 0x1000, avail caps 0x4
    744[7161040]: (GSSAPI = 0x1000000, CRAM = 0x20000, NTLM = 0x100000, MSN = 0x200000, PLAIN = 0x1000, LOGIN = 0x2, old-style IMAP login = 0x4)auth external IMAP login = 0x20000000
    744[7161040]: trying auth method 0x4
    744[7161040]: got new password
    744[7161040]: IMAP: trying auth method 0x4
    744[7161040]: old-style auth
    744[7161040]: 7082000:xmail.xmail.domain.com:NA:SendData: Logging suppressed for this command (it probably contained authentication information)
    744[7161040]: ReadNextLine [stream=7ec9e88 nb=23 needmore=0]
    744[7161040]: 7082000:xmail.domain.com:NA:CreateNewLineFromSocket: 4 OK LOGIN completed.
    744[7161040]: login succeeded
    --> okay, so Thunderbird is using "old-style IMAP login" and is successful.
    Unfortunately I have no idea what that actually means or how to use it in Javamail (is it even supported?). Any suggestions?

  • Here's how you use JavaMail in a Netscape 4.x applet

    First of all... Sun has said that they are working on patching JavaMail for the next minor release so that it will be usable with Netscape.
    But for those with itchy pants... here's how you do to send mail from a Netscape 4.x applet without using the Java Plug-in.
    First of all... you'll need to sign the applet. Now I'm not so good with singing tools so I don't know if Netscape 4.x allows using Sun's signing tools. I used Netscapes own "signtool" just to be sure.
    You'll need to unjar activation.jar and mail.jar (or mailapi.jar plus smtp.jar). Use signtool to sign and jar your own classfiles plus those from the jar-files mentioned.
    This creates a small problem though: atcivation.jar and mail.jar has files in the META-INF directory. Netscapes signtool ignores these files. So you'll have to patch around that.
    Using the "sendfile.java" demo as basis... here's how you deal with the missing configuration files.
        // You'll have to request this privilige or Netscape will bolt on you.
        // If you need cross-platfor compatibility you'll need to wrap this up or IE
        // will be really cranky at this. Try by doing something you know
        // IE accepts but that Netscape don't. Catch the  exception as just an
        // Exception and do the following in the catch.
        try {
          PrivilegeManager.enablePrivilege("UniversalPropertyRead");
        } catch (netscape.security.ForbiddenTargetException e2) {
          System.out.println("Failed! Permission to read system properties denied by user.");
        } catch (Exception e2) {
          System.out.println("Failed! Unknown exception while enabling privilege.");
          e2.printStackTrace(System.out);
        // create some properties and get the default Session
        Properties props = null;
        props = System.getProperties();
        props.put("mail.smtp.host", mailhost);
        // The mailcap command map needs a missing
        // config file. So you'll have to hardwire the different
        // commands like this.
        javax.activation.MailcapCommandMap commandMap = new javax.activation.MailcapCommandMap();
        commandMap.addMailcap("text/plain;;          x-java-content-handler=com.sun.mail.handlers.text_plain");
        commandMap.addMailcap("text/html;;          x-java-content-handler=com.sun.mail.handlers.text_html");
        commandMap.addMailcap("text/xml;;          x-java-content-handler=com.sun.mail.handlers.text_xml");
        commandMap.addMailcap("multipart/*;;          x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
        commandMap.addMailcap("message/rfc822;;     x-java-content-handler=com.sun.mail.handlers.message_rfc822");
        commandMap.addMailcap("image/gif;;          x-java-view=com.sun.activation.viewers.ImageViewer");
        commandMap.addMailcap("image/jpeg;;          x-java-view=com.sun.activation.viewers.ImageViewer");
        commandMap.addMailcap("text/*;;          x-java-view=com.sun.activation.viewers.TextViewer");
        commandMap.addMailcap("text/*;;          x-java-edit=com.sun.activation.viewers.TextEditor");
        javax.activation.MailcapCommandMap.setDefaultCommandMap(commandMap);
        // Now here is a really weird thing. This class - MimeUtility - will
        // be used later on. But the ClassLoader in Netscape seems
        // to be broken. I downloaded J2EE and fiddled with this class a bit.
        // It seems that the following line will get you around this problem.
        Object o = MimeUtility.class;
        try {
          // create a message
          Session session = Session.getDefaultInstance(props, null);
          session.setDebug(true);
          MimeMessage msg = new MimeMessage(session);
          msg.setFrom(new InternetAddress(from));
          InternetAddress[] address = {new InternetAddress(to)};
          msg.setRecipients(Message.RecipientType.TO, address);
          msg.setSubject("Message from scratchpad");
          // create and fill the first message part
          MimeBodyPart mbp1 = new MimeBodyPart();
          mbp1.setText(message);
          // create the second message part
          MimeBodyPart mbp2 = new MimeBodyPart();
          // attach the file to the message
          // This is not the same as the original.
          // The ByteArrayDataSource class helps you attach an arbitrary file-type.
          // The code for that is found here:
          // http://forums.java.sun.com/thread.jsp?forum=43&thread=73819
          DataSource ds = new ByteArrayDataSource(imageData, "image/gif", "image.gif");
          mbp2.setDataHandler(new DataHandler(ds));
          mbp2.setFileName("image.gif");
          // 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() will give you exception in Netscape.
          // Here is how you do what that method does.
          msg.saveChanges();
          com.sun.mail.smtp.SMTPTransport transport = new com.sun.mail.smtp.SMTPTransport(session, null);
          transport.connect();
          transport.sendMessage(msg, address);
          transport.close();     
        catch (MessagingException mex) {
          mex.printStackTrace();
          Exception ex = null;
          if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }Enjoy
    /Michael

    Typical... i knew I'd fumble. There is one more thing you need to do.
    Download J2EE, source code edition and patch the file javax.mail.internet.MimeUtility.java
    Change the line
    InputStream is = javax.mail.internet.MimeUtility.class.getResourceAsStream("/META-INF/javamail.charset.map");...to...
    InputStream is = javax.mail.internet.MimeUtility.class.getResourceAsStream("/javamail.charset.map");Also, after you unjar the jarfiles and before you run the signtool, move the file META-INF/javamail.charset.map to the partent of the META-INF directory.
    /Michael

  • Urgent!!!!!How can i use javamail in jsp without using javabeans

    hello friend
    I m making a forum in which i want to send response to the user through mail I m not using javabean Can anyone help me.How to use javamail in jsp

    http://java.sun.com/developer/onlineTraining/JavaMail/exercises.html

  • How to bypass proxy when trying to send a mail using javamail smtp

    Hi,
    I am trying to make a servlet send a mail using javamail smtp protocol on port 25 but i m not able to send getting an exception, i suspect proxy is blocking, so any idea anyone how bypass a proxy.

    And if it does turn out that there's a proxy server blocking access to your target SMTP server, the best way to deal with that is to discuss the issue with the person responsible for your network configuration.

  • How to read emails using javamail

    hello friends
    well i am working on a project on phishing for that i had usinf javamail to read out the mails while i open my any email account while i working on the net .
    actually what i want is whenever i open my account my program could detect the mail and it will it work after that
    so can anyone please help me out in doing this means my first problem is how to get my program get linked with that so that everytime i opem my email account (not specific) i can use the message stuff written in that for my further use
    please help me guys i really need help
    please reply as soon as possible
    thanks

    i could not understand your problem exactly.
    if you mean you want to check the new messages count: you can simply used
    int newMessages = folder.getNewMessageCount();if you are reading mails first time using javamail.
    see http://itoday.wordpress.com/2007/04/08/sending-mail-using-javamail-apis/
    if you mean something else ... please let me know
    asif shahzad
    Edited by: asifsh7 on Jul 22, 2008 8:53 AM

  • How to send a Meeting Request to Exchange/Outlook using JavaMail

    Hi,
    Can any body help me "How to send a Meeting Request to Exchange/Outlook using JavaMail" which will be added to the calendar items.
    If possible, please provide me with the sample code. Please send the sample code to the following mail id: "[email protected]".
    Thanks in advance,
    Ashok.

    I don't have a homework problem. I have a real business need for this, but haven't been able to get my code to work yet. There are at least two references out there, but either the sample code hasn't been posted or I don't know where to look. Can you help?
    Thanks.

  • How to attach a file to an email without using JavaMail

    hi everyone!
    I'm trying to develope a program wich has to send email messages with attached files. Specifications say that I can't use JavaMail. So I'm trying to use SMTP. It's a very simple protocol, but I haven't found how to send attached files.
    Any suggestion or source code? Thanx Very much!!!

    you will need to add a mime body to the data as done in the example message (i found it somewhere on teh internet so don't blame me for erors in it ;) )
    MAIL FROM:<[email protected]>
    RCPT TO:<[email protected]>
    DATA
    Mime-version: 1.0
    Content-Type: multipart/mixed; boundary=OpenVMS/MIME.572522828.951855
    Content-Transfer-Encoding: 7bit
    Message-ID: <572522828.0@>
    --OpenVMS/MIME.572522828.951855736
    Content-Type: text/plain; charset=ISO-8859-1
    Content-Transfer-Encoding: 7bit
    Content-Disposition: inline
    We have modified this to send with SFF for SMTP - TCPIP
    Services for OpenVMS.
    --OpenVMS/MIME.572522828.951855736
    for info about how to use mime look at the RFC of mime (just do a google search)
    Robert

  • Please,how can I use javamail to implementing draft box on webmail

    please,how can I use javamail to implementing draft box on webmail

    I already can send and receive EMail ��create
    subfolder with javamail in imap server.but I don't
    know how implement draft mailbox with webmail .
    please expert help me . thanksyou can only create subfolders in a imap mail server ,and you can use folder class included in javamail api to access,create,modify and delete subfolders.You also can create subfolders under a subfolder as you want.
    the simple example is:
    //first create mail session
    mailSession=...
    // second create mail store
    mailStore=...
    //third get root folder
    IMAPFolder rootFolder = (IMAPFolder)mailStore.getFolder("INBOX");
    if ((rootFolder==null)||(!rootFolder.exists())) return false;
    //finally create a subfolder "outbox" under root folder "inbox"
    IMAPFolder tmpOutFolder = (IMAPFolder)rootFolder.getFolder("OUTBOX");
    if (tmpOutFolder==null) return false;
    //if the target folder not exist just create it
    //note:when you create a subfolder you can assign its attribute.Details,please read the javamail document.
    if(!tmpOutFolder.exists()) tmpOutFolder.create(Folder.HOLDS_MESSAGES);

  • How to setup SMTP server  in PC so as to send mails using JavaMail

    Hi,
    From forums i got it cleared that we can use JavaMail to send emails. I also got two sample codes about getting it done. But in the code its asks address of the host of SMTP server. I dont have any SMTP server. But i am writing a Library Application in which an email must be sent to users automatically when thier books are in overdue.
    Where can i get SMTP server to be installed on my PC so that i can use it send mails through Javamail API.
    Thanks

    Isnt there any way setup SMTP server on own pc?? I just want to send mails in my local area network.

  • How to Reply to a Mail Using Javamail?

    Hi Friends,
    My Requirement is to reply to a email came froom sender mail.
    and i want to send a reply email to my sender using JavaMail program.
    I was sucessful in sending mails with attachments and i can retrive
    plain mails i mean text mails,with attachments and all and all.
    and also i have create an interface that will send mails
    with attachments to the Recipients.
    If any body knows the solution for this post me,
    if possible post the code snipnet.
    Thanks
    Regrads
    Nagaraju .g

    And if it does turn out that there's a proxy server blocking access to your target SMTP server, the best way to deal with that is to discuss the issue with the person responsible for your network configuration.

  • How to send one email to multi-users using JavaMail ?

    I am using JavaMail API. I am working in "sending emails to users", I had already tested "one email to one user" and got success but when tried to send one email to multi-users then I failed to do that?
    Can anyone help me to do this?
    I have used the below code to send to multi-user:
    Address[] toAddr = {new InternetAddress(_to),new InternetAddress (to2)};
    msg.addRecipients(Message.RecipientType.TO, toAddr);
    But it is static only 2 users. I want to send to multi-users dynamically taking datas from database.
    I have tried by using below code but it doesn't work.....
    InternetAddress[] emails;
    while (resultset.next()) {
    temp = resultset.getString(1);
    emails.setAddress(temp);
    i++;
    Address[] toAddr = emails;
    msg.addRecipients(Message.RecipientType.TO, toAddr);
    Thank you in advance...
    -ritesh

    I think you're confused about some basic Java programming techniques.
    There are two obvious ways to do this.
    1. Call the addRecipient method in a loop.
    2. Collect all the recipients in a List, convert it to an array, and call addRecipients.

  • Problem Sending mails in a loop using JavaMail API

    Hello All,
    I am sending emails in a loop(one after the other) using JavaMail API,but the problem is, if the first two,three email addresses in the loop are Valid it sends the Email Properly, but if the Fourth or so is Invalid Address it throws an Exception....
    "javax.mail.SendFailedException: Sending failed;"
    nested exception is:
    javax.mail.SendFailedException: Invalid Addresses;
    nested exception is:
    javax.mail.SendFailedException: 450 <[email protected]>:Recipient address rejected: Domain not found......
    So if i want to send hundereds of emails and if one of the Emails inbetween is Invalid the process Stops at that point and i could not send the other emails in the Loop......
    How Could i Trap the exception thrown and handle it in such a way, so that the loops continues ..
    Is there something with the SMTP Server....?
    The code which i am using is as follows....
    <Code>...
    try {
    InitialContext ic = new InitialContext();
    Session session = (Session) ic.lookup(JNDINames.MAIL_SESSION);
    if (Debug.debuggingOn)
    session.setDebug(true);
    // construct the message
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(eMess.getEmailSender()));
    String to = "";
    msg.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse(to, false));
    msg.setRecipients(Message.RecipientType.BCC,
    InternetAddress.parse(eMess.getEmailReceiver(), false));
    msg.setSubject(eMess.getSubject());
    msg.setContent(eMess.getHtmlContents(),"text/plain");
    msg.saveChanges();                
    Transport.send(msg);
    } catch (Exception e) {
    Debug.print("createAndSendMail exception : " + e);
    throw new MailerAppException("Failure while sending mail");
    </Code>....
    Please give me any suggestions regarding it....and guide me accordingly..
    Thanks a million in advance...
    Regards
    Sam

    How about something like the code attached here. Be aware it is lifted and edited out of an app we have here so it may require changing to get it to work. If it don't work - don't come asking for help as this is only a rough example of one way of doing it. RTFM - that's how we worked it out!
    SH
    try {
    Transport.send(msg);
    // If we get to here then the mail went OK so update all the records in the email as sent
    System.out.println("Email sent OK");
    catch (MessagingException mex) {
    System.out.println("Message error");
    Exception ex = mex;
    do {
    if (ex instanceof SendFailedException) {
    if (ex.getMessage().startsWith("Sending failed")) {
    // Ignore this message as we want to know the real reason for failure
    // If we get an Invalid Address error or a Message partially delivered message process the message
    if (ex.getMessage().startsWith("Message partially delivered")
    || ex.getMessage().startsWith("Invalid Addresses")) {
    // This message is of interest as we need to process the actual individual addresses
    System.out.println(ex.getMessage().substring(0, ex.getMessage().indexOf(";")));
    // Now get the addresses from the SendFailedException
    SendFailedException sfex = (SendFailedException) ex;
    Address[] invalid = sfex.getInvalidAddresses();
    if (invalid != null) {
    System.out.println("Invalid Addresse(s) found -");
    if (invalid.length > 0) {
    for (int x = 0; x < invalid.length; x++) {
    System.out.println(invalid[x].toString().trim());
    Address[] validUnsent = sfex.getValidUnsentAddresses();
    if (validUnsent != null) {
    System.out.println("Valid Unsent Addresses found -");
    if (validUnsent.length > 0) {
    for (int x = 0; x < validUnsent.length; x++) {
    System.out.println(validUnsent[x].toString().trim());
    Address[] validSent = sfex.getValidSentAddresses();
    if (validSent != null) {
    System.out.println("Valid Sent Addresses found -");
    if (validSent.length > 0) {
    for (int x = 0; x < validSent.length; x++) {
    System.out.println(validSent[x].toString().trim());
    if (ex instanceof MessagingException)
    ex = ((MessagingException) ex).getNextException();
    else {
    // This is a general catch all and we should assume that no messages went and should stop
    System.out.println(ex.toString());
    throw ex;
    } while (ex != null);

Maybe you are looking for