Gettting attachments using JAVAMAIL

Hi,
I am dealing with an application which wants me to go through the mailbox and get the attachments of specific emails. These attachments are of different kinds. The attachments can vary from being rtf document, to Word, html, fo.. documents.. I got this skeleton code from the tutorial but dont know what to fill in..
if (disposition == null) {
// Check if plain
MimeBodyPart mbp = (MimeBodyPart)part;
if (mbp.isMimeType("text/plain")) {
// Handle plain
} else {
// Special non-attachment cases here of
// image/gif, text/html, ...
What is it meant by handling plain? How do i handle html, worf, rtf documents.. Thanks a lot in advance.. Thanks
Abhishek

Try this as a reference. It works PERFECTLY. Ignore the comments.
//If the content is ATTACHMENT
filename = part.getFileName();
if (filename != null) {
filename = filename.trim();
if(filename.equalsIgnoreCase(fileNameDownload.trim())) {
                                        //System.out.println("Downloading DOWN 1");
                                        session_id = this.DL_sessionid;
                                        directory = ATTACHMENTPath + m_user + "_" + session_id + "/";
                                        if(download) {
                                             pushFile(part.getFileName(),part.getInputStream(),resp);
                                        } else {
                                             saveFile(part.getFileName(), directory, part.getInputStream(), resp);
                                   filectr++;
     private void saveFile(String fileName, String Directory, InputStream input, HttpServletResponse resp)
          String myfile="";
          try
               //Correct the file name;
               String p_filename = javaFileParser(fileName);
               File newDir = new File(Directory);
               //Check if the directory does not exists!
               if(!newDir.exists()) { //If it doesn't..
                    //Create the directory
                    newDir.mkdir();
               String complete_path = Directory + p_filename;
               File myFile=new File(complete_path);
               //Check if a filename like this already exists!
               if(myFile.exists()) {
                    //If it does..
                    //delete the current file residing into the directory
                    myFile.delete();
               //Write the file (START)
               FileOutputStream fos = new FileOutputStream(myFile);
               BufferedOutputStream bos = new BufferedOutputStream(fos);
               BufferedInputStream bis = new BufferedInputStream(input);
               int aByte;
               while ((aByte = bis.read()) != -1)
               bos.write(aByte);
               bos.flush();
               bos.close();
               bis.close();
               //(END)
          catch (Exception x)
               System.out.println("Error : " + x);
     private void pushFile(String fileName,InputStream input, HttpServletResponse resp)
          try
               //Download the file to the Client's machine
               ServletOutputStream stream = resp.getOutputStream();
               resp.setContentType("application/octet-stream");
               resp.setHeader("Content-Disposition","attachment;filename="+fileName.trim()+";");
               //BufferedInputStream fif = new BufferedInputStream(new FileInputStream(complete_path));
               BufferedInputStream fif = new BufferedInputStream(input);
               int data;
               while((data = fif.read()) != -1)
               stream.write(data);
               stream.flush();
               fif.close();
               stream.close();
          catch (Exception x)
               System.out.println("Error : " + x);
     private String javaFileParser(String filename)
          //System.out.println("In EmailObject javaFileParser");
          String n_filename="";
          //Check if the file starts with '=?iso8859'
          //If it does, it will need parsing
          if(filename.startsWith("=?iso")) {
               n_filename = filename.substring(15,filename.lastIndexOf("?"));
          } else
               n_filename = filename;
          return n_filename;
I suggest don't use JavaMail.. It has BUGS on some other email type. If not in POP3 then in IMAP.. Specialy when it receives "Enriched" contents types. Better yet don't use Java. It has lots of Bugs.

Similar Messages

  • Sending Attachments using JavaMail

    I trying to send attachments using JavaMail API which is loaded into an oracle 8.1.7 database as a stored procedure, the code looks like this:-
    CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "SendMail" AS
    import java.util.*;
    import java.io.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    public class SendMail {
    // Sender, Recipient, CCRecipient, and BccRecipient are comma-
    // separated lists of addresses;
    // Body can span multiple CR/LF-separated lines;
    // Attachments is a ///-separated list of file names;
    public static int Send(String SMTPServer,
    String Sender,
    String Recipient,
    String CcRecipient,
    String BccRecipient,
    String Subject,
    String Body,
    String ErrorMessage[],
    String Attachments) {
    // 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);
    // extracts the senders and adds them to the message;
    // Sender is a comma-separated list of e-mail addresses as
    // per RFC822;
    InternetAddress[] TheAddresses =
    InternetAddress.parse(Sender);
    msg.addFrom(TheAddresses);
    // extract the recipients and assign them to the message;
    // Recipient is a comma-separated list of e-mail addresses
    // as per RFC822;
    InternetAddress[] TheAddresses =
    InternetAddress.parse(Recipient);
    msg.addRecipients(Message.RecipientType.TO,
    TheAddresses);
    // extract the Cc-recipients and assign them to the
    // message;
    // CcRecipient is a comma-separated list of e-mail
    // addresses as per RFC822;
    if (null != CcRecipient) {
    InternetAddress[] TheAddresses =
    InternetAddress.parse(CcRecipient);
    msg.addRecipients(Message.RecipientType.CC,
    TheAddresses);
    // extract the Bcc-recipients and assign them to the
    // message;
    // BccRecipient is a comma-separated list of e-mail
    // addresses as per RFC822;
    if (null != BccRecipient) {
    InternetAddress[] TheAddresses =
    InternetAddress.parse(BccRecipient);
    msg.addRecipients(Message.RecipientType.BCC,
    TheAddresses);
    // subject field;
    msg.setSubject(Subject);
    // create the Multipart to be added the parts to;
    Multipart mp = new MimeMultipart();
    // create and fill the first message part;
    MimeBodyPart mbp = new MimeBodyPart();
    mbp.setText(Body);
    // attach the part to the multipart;
    mp.addBodyPart(mbp);
    // attach the files to the message;
    if (null != Attachments) {
    int StartIndex = 0, PosIndex = 0;
    while (-1 != (PosIndex = Attachments.indexOf("///",
    StartIndex))) {
    // create and fill other message parts;
    MimeBodyPart mbp = new MimeBodyPart();
    FileDataSource fds =
    new FileDataSource(Attachments.substring(StartIndex,
    PosIndex));
    mbp.setDataHandler(new DataHandler(fds));
    mbp.setFileName(fds.getName());
    mp.addBodyPart(mbp);
    PosIndex += 3;
    StartIndex = PosIndex;
    // last, or only, attachment file;
    if (StartIndex < Attachments.length()) {
    MimeBodyPart mbp = new MimeBodyPart();
    FileDataSource fds =
    new FileDataSource(Attachments.substring(StartIndex));
    mbp.setDataHandler(new DataHandler(fds));
    mbp.setFileName(fds.getName());
    mp.addBodyPart(mbp);
    // 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 MsgException) {
    ErrorMessage[0] = MsgException.toString();
    Exception TheException = null;
    if ((TheException = MsgException.getNextException()) !=
    null)
    ErrorMessage[0] = ErrorMessage[0] + "\n" +
    TheException.toString();
    ErrorStatus = 1;
    return ErrorStatus;
    show errors java source "SendMail"
    CREATE OR REPLACE PACKAGE SendMailJPkg AS
    -- EOL is used to separate text line in the message body;
    EOL CONSTANT STRING(2) := CHR(13) || CHR(10);
    TYPE ATTACHMENTS_LIST IS
    TABLE OF VARCHAR2(4000);
    -- high-level interface with collections;
    FUNCTION SendMail(SMTPServerName IN STRING,
    Sender IN STRING,
    Recipient IN STRING,
    CcRecipient IN STRING DEFAULT '',
    BccRecipient IN STRING DEFAULT '',
    Subject IN STRING DEFAULT '',
    Body IN STRING DEFAULT '',
    ErrorMessage OUT STRING,
    Attachments IN ATTACHMENTS_LIST DEFAULT NULL)
    RETURN NUMBER;
    END SendMailJPkg;
    show errors
    CREATE OR REPLACE PACKAGE BODY SendMailJPkg AS
    PROCEDURE ParseAttachment(Attachments IN ATTACHMENTS_LIST,
    AttachmentList OUT VARCHAR2) IS
    AttachmentSeparator CONSTANT VARCHAR2(12) := '///';
    BEGIN
    -- boolean short-circuit is used here;
    IF Attachments IS NOT NULL AND Attachments.COUNT > 0 THEN
    AttachmentList := Attachments(Attachments.FIRST);
    -- scan the collection, skip first element since it has been
    -- already processed;
    -- accommodate for sparse collections;
    FOR I IN Attachments.NEXT(Attachments.FIRST) ..
    Attachments.LAST LOOP
    AttachmentList := AttachmentList || AttachmentSeparator ||
    Attachments(I);
    END LOOP;
    ELSE
    AttachmentList := '';
    END IF;
    END ParseAttachment;
    -- forward declaration;
    FUNCTION JSendMail(SMTPServerName IN STRING,
    Sender IN STRING,
    Recipient IN STRING,
    CcRecipient IN STRING,
    BccRecipient IN STRING,
    Subject IN STRING,
    Body IN STRING,
    ErrorMessage OUT STRING,
    Attachments IN STRING) RETURN NUMBER;
    -- high-level interface with collections;
    FUNCTION SendMail(SMTPServerName IN STRING,
    Sender IN STRING,
    Recipient IN STRING,
    CcRecipient IN STRING,
    BccRecipient IN STRING,
    Subject IN STRING,
    Body IN STRING,
    ErrorMessage OUT STRING,
    Attachments IN ATTACHMENTS_LIST) RETURN NUMBER IS
    AttachmentList VARCHAR2(4000) := '';
    AttachmentTypeList VARCHAR2(2000) := '';
    BEGIN
    ParseAttachment(Attachments,
    AttachmentList);
    RETURN JSendMail(SMTPServerName,
    Sender,
    Recipient,
    CcRecipient,
    BccRecipient,
    Subject,
    Body,
    ErrorMessage,
    AttachmentList);
    END SendMail;
    -- JSendMail's body is the java function SendMail.Send();
    -- thus, no PL/SQL implementation is needed;
    FUNCTION JSendMail(SMTPServerName IN STRING,
    Sender IN STRING,
    Recipient IN STRING,
    CcRecipient IN STRING,
    BccRecipient IN STRING,
    Subject IN STRING,
    Body IN STRING,
    ErrorMessage OUT STRING,
    Attachments IN STRING) RETURN NUMBER IS
    LANGUAGE JAVA
    NAME 'SendMail.Send(java.lang.String,
    java.lang.String,
    java.lang.String,
    java.lang.String,
    java.lang.String,
    java.lang.String,
    java.lang.String,
    java.lang.String[],
    java.lang.String) return int';
    END SendMailJPkg;
    show errors
    var ErrorMessage VARCHAR2(4000);
    var ErrorStatus NUMBER;
    -- enable SQL*PLUS output;
    SET SERVEROUTPUT ON
    -- redirect java output into SQL*PLUS buffer;
    exec dbms_java.set_output(5000);
    BEGIN
    :ErrorStatus := SendMailJPkg.SendMail(
    SMTPServerName => 'gmsmtp03.oraclecorp.com',
    Sender => '[email protected]',
    Recipient => '[email protected]',
    CcRecipient => '',
    BccRecipient => '',
    Subject => 'This is the subject line: Test JavaMail',
    Body => 'This is the body: Hello, this is a test' ||
    SendMailJPkg.EOL || 'that spans 2 lines',
    ErrorMessage => :ErrorMessage,
    Attachments => SendMailJPkg.ATTACHMENTS_LIST(
    '/tmp/on.lst',
    '/tmp/sqlnet.log.Z'
    END;
    print
    If I try and send file as attachments from the tmp directory, then everything works ok, but if I try to send the same file from any other directory, then it doesn't work. Can anyone help? Is there something wrong with the code, I'm not aware of anything that would make it directory specfic. Permissions are the same on /tmp as the new directory /NRS/Data/SystemX which I'm trying to send the file from now.

    well
    if u see the end of ur mail it shows the attachment dir there in which u have specified the address..why don't u do a change there or better have some in parameteres in the procedure for it..that would help in choosing the attachment directory on users wish?
    hope i am getting the problem right..if not kindly correct me in understanding the problem.
    thanX.

  • Parsing email attachments using Javamail

    Hi All,
    I'm working on a multimedia application where I have to parse emails using Javamail.
    Here is a problem that i'm facing.
    When i'm receiving an attachment from icloud.com, i'm not able to get the filename whereas i'm able to get the fileSize and fileContent.
    I'm using Part.getFileName() to get the file name. and Part.getFileSize() and Part.getInputStream() to get size and the content.
    When i checked the attachment header, I could see the name encoded in ISO-8859-1.
    --Boundary_(ID_kS5Ng+OB35IVBfC+scPoMA)
    Content-id:[email protected]
    Content-type:image/jpeg;
    name*1*=utf-8"%20%32%33%30%32%32%30%31%33%37%32%35;
    name*2*=%2E%6A%70%67
    Content-transfer-encoding:BASE64
    Content-disposition:inline;
    filename*1*=utf-8"%20%32%33%30%32%32%%30%32%33%37%32%35
    filename*2*=%2E%6A%70%67
    In both the cases above, Part.getFileName() is returning null.
    I set the parameter mail.mime.decodeparameters="true".Still it is not working.
    It would be great if someone can suggest a solution for this.
    Thanks
    Shyama

    Just adding to the problem description:
    --Boundary_(ID_kzWHPgILjZtH2UtdriatGg)
    Content-id: <[email protected]>
    Content-type: image/jpeg; name*1*=ISO-8859-1''%32%2E%6A%70%67
    Content-transfer-encoding: BASE64
    Content-disposition: inline; filename*1*=ISO-8859-1''%32%2E%6A%70%67
    This is the header which could see in another mail.

  • URGENT : Multiple Attachments using JavaMail

    Hello ,
    I'm trying to send multiple attachments to a single mailid. I have 3 text boxes in my JSP page which holds the file name that is selected . in the next page i retrieving the values of those filenames and sending it as attachment .
    But when i do so , i'm getting NullPointeException when one of 2 file is choose . but when i choose 3 files to send , it is working fine . Can any one help pls,
    Here is the code
    public class Attachservlet extends HttpServlet{
         public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{
         String host="172.30.1.35";
         String full[]=new String[3];
         String part[]=new String[3];
         String fname[]=new String[3];
         String pname[]=new String[3];
         String ss[]=new String[3];
         String name[]=new String[3],conc="";
         int j,jj;
         String sender_email=req.getParameter("senderemail");
         String sender_name=req.getParameter("sendername");
         String receiver_email=req.getParameter("receiveremail");
         String receiver_name=req.getParameter("receivername");
         String sent_message=req.getParameter("area");
         PrintWriter out=res.getWriter();
         Properties props=System.getProperties();
         props.put("mail.smtp.host",host);
         Session session=Session.getDefaultInstance(props,null);
         MimeMessage message=new MimeMessage(session);
         try{
         for ( jj=0;jj<3;jj++){
         j=jj+1;
         name[jj]="filename"+j;
         pname[jj]="pname"+j;
         ss[jj]=req.getParameter(name[jj]);
         part[jj]=req.getParameter(pname[jj]);
         if(ss[jj].length()!=0){
         System.out.println("values is "+ss[jj] +"\n"+part[jj]);
         System.out.println("values is "+ss[jj] +"\n"+part[jj]);
         conc=conc+ss[jj]+",";
         System.out.println(conc);     
         message.setFrom(new InternetAddress(sender_email,"Sumathi"));
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(receiver_email));
         message.setSubject(receiver_name);
         BodyPart bodypart=new MimeBodyPart();
         bodypart.setText(sent_message);
         Multipart multi=new MimeMultipart();
         multi.addBodyPart(bodypart);
         bodypart = new MimeBodyPart();
         DataSource source=new FileDataSource("test.jsp");
         bodypart.setDataHandler(new DataHandler(source));
         bodypart.setFileName(part[jj]);
         multi.addBodyPart(bodypart);
         message.setContent(multi);
         Transport.send(message);
         res.sendRedirect("http://sumathi/Mail/Success.jsp");
         System.out.println("Message Sent");
         }catch(Exception e){
         System.err.println("An Exception has Arrised \t"+e);
         public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException{
         doPost(req,res);
    Any Help pls ,
    Thanks in Advance !

    OK,
    Although you didn't post the stack trace from your NullPointer, my guess is that it's being thrown at this line:
    if(ss[jj].length()!=0){
    your ss[jj] variable is being assigned the value: req.getParameter(name[jj]); This value is null in the case when you have anything less that 3 parameters in your form.
    You need to check for a null value at this point.

  • Problem with sending large HTML files as attachment using JavaMail 1.2

    Hi dear fellows, i am currently working on posting Emails with attachments using JavaMail 1.2. i succeeded in sending many mimetypes of files as attachments except for .htm and .html files. when large HTML files (say, >100 kB) serve as attachements, the mail is posted on mail server, but not properly posted since only the first small part of the file is writted into mail server but the latter part of the attachment file is missing.
    is that a bug of JavaMail??? are there any fellows encountering similar problem as i did??? any suggestions for me to proceed? hopefully i made myself clear...
    Many thanks in advance,
    Fatty

    i've sort of found the cause for that, it is because when the stream write to the mail server, unfortunately there is a "." in a single line. so the server refuse to take any more inputs.
    so do i have to remove all the "." in the file manually to avoid this disaster? any suggestions??
    Fatty

  • Using attachments with javamail

    Hi
    I wonder if anyone could help me. Is is possible to send an (oracle)blob as an attachment using javamail? How would I go about doing this? Thanks in advance

    You can attach arbitrary binary data to an email sent through javamail. How the recipient interprets that data depends on the mime type and on their email client. I think a mime type of application/octet-stream will result in a binary file for which the only option is saving to disk.
    Below are code snippets from part of a program in which I deal with attachments. They are far from complete, but show all the important method calls.
    import javax.mail.*;
    import javax.mail.internet.*;
    attachment = (NotifyInterface.Attachment)allData.getObject();
    headers = new InternetHeaders();
    headers.addHeader("Content-Type", attachment.getMimeType());
    encodedData = base64Encode(attachment.getData());
    mbpAttachment=new MimeBodyPart(headers, encodedData);
    mbpAttachment.setFileName(attachment.getFileName());
    mbpAttachment.setDisposition(MimeMessage.ATTACHMENT);
    mbpAttachment.setHeader("Content-Transfer-Encoding", "base64");
    byte[] base64Encode(byte[] rawData) throws MessagingException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    OutputStream out = MimeUtility.encode(bout, "base64");
    try {
    out.write(rawData);
    out.close();
    } catch(IOException e) {
    throw (MessagingException)new MessagingException("Error encoding attachment").initCause(e);
    return bout.toByteArray();
    public static class Attachment implements Serializable {
    String fileName;
    String mimeType;
    byte[] data;
    public Attachment(String fileName, byte[] data, String mimeType) {
    this.fileName = fileName;
    this.data = data;
    this.mimeType = mimeType;
    public String getFileName() {
    return fileName;
    public String getMimeType() {
    return mimeType;
    public byte[] getData() {
    return data;
    public String toString() {
    return "Attachment of type "+mimeType;

  • Download attachments from gmail using javamail

    I want to download the selected attachments from my gmail accout by using javamail.Is it possible?How can i acheive this?
    The actual need is i want to download only the selected files from my attachments.
    Thanks,
    vino

    I have downloaded attachments from my gmail account to local drive by using JavaMailApi.
    i will show the message subjects in my webpage.If i click the subject the corresponding attachment will be download.
    Here i have two questions,
    1)Can i display the attachment files in my page?
    2)I want to download the selected file from an attachment.suppose If i have an attachment with 5 files.
    and i select the 3rd file then the 3rd file will be download.how can i do it?

  • Reading attachments via Javamail gives ? characters

    Hi,
    I'm using Javamail to read messages in a mailbox and to save the attachments that are on those messages. Some attachments are HTML documents that seem to contain bullet characters (doing a View Source on the HTML still shows the bullet, not "<li>" or anything like that). The HTML documents have UTF-8 set as their encoding type.
    A snippet of the code I'm using to retrieve and save the attachments is shown below :-
    File file = new File(<filename to save the attachment>);
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    BufferedInputStream bis = new BufferedInputStream(part.getInputStream());
    int aByte;
    while ((aByte=bis.read()) !=-1)
         bos.write(aByte);
    bos.flush();
    bos.close();
    bis.close();
    When I look at the saved file I always see a question mark character instead of the bullet.
    I think it's a character set problem but can anyone offer some advice ?
    Thanks in advance.

    The file is going to be saved using the same encoding as was used
    in the message, probably utf-8. If the program you use to view the
    file is assuming a different encoding, e.g., the OS's default encoding,
    you're not going to see what you expect.
    You might want to convert the file to the OS's default encoding.
    You can do that using Java by using a Reader to read the stream,
    telling it the charset used on the mail body part, and write the
    data to a Writer using the default encoding.

  • 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.

  • I am not able to fetch size of a Attachment part using Javamail classes

    Hi All,
    I am using javamail classes to read mails from my email system.
    the message i am reading is MIME Multipart and it has got attachments.
    One of the attachment is 'application/smil' type.
    I am not seeing its size properly but I am able to open the message correctly.
    Is this a problem with rendering the message?
    Any help would be greatly appreciated.
    Thanks,
    Amit

    Hi,
    Following is the code to render the part. It would be great if you can suggest something to modify and correct the problem.
    As you said in your eariler reply, I am determining size by rendering attachment as one of the mime part.
    Thanks,
    Amit
         * Renders the specified part.
         * @param part part to be rendered
         * @return the modified message part
         * @throws MessagingException on JavaMail errors
         * @throws IOException on errors getting part contents
         * @throws RenderingException on problems rendering part content
        private Part renderPart(Part part)
                throws MessagingException, IOException, RenderingException {
            int partIndex = listSize;
            // Part has been displayed on another page and doesn't
            // need to be rendered.
            if (partIndex < state.getPartIndex()) {
                return null;
            } else if (partIndex != state.getPartIndex()) {
                state = new State(partIndex, "0");
            // Part is not renderable so return it.
            if (!part.isMimeType(MIME_TEXT) &&
                !part.isMimeType(MIME_DISPOSITION_NOTIFICATION)) {
                return part;
            String charset = null;
            try {
                part = MailUtils.repairContentTranscoding(part);
                ContentType type = getNormalizedContentType(part);
                if (logger.isDebugEnabled()) {
                    logger.debug("Part[" + state.getPartIndex() +
                            "].ContentType: " + type);
                charset = type.getParameter("charset");
                if (charset != null && charset.length() > 0) {
                    charset = MimeUtility.javaCharset(charset.trim());
                    try {
                        if (!Charset.isSupported(charset)) {
                            logger.warn("Unsupported charset: \"" + charset + "\"");
                            charset = null; // Ignore, use default charset
                    } catch (IllegalCharsetNameException icne) {
                        logger.warn("Illegal charset name: \"" + charset + "\"");
                        charset = null; // Ignore, use default charset
            } catch (MessagingException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug(e.getMessage(), e);
                charset = null; // Ignore, use default charset
            if (charset == null || charset.length() == 0) {
                if (state.getPartIndex() == 0) {
                    // It is *Message body*
                    // charset is not in Mime Header, so need to detect
                    // the charset.
                    charset = (String) setup.get("client.defaultEmailCharset");
                } else {
                    // It is *Attachment*
                    // charset is not in Mime Header, so need to detect
                    // attached file charset.
                    charset = (String) setup.get("client.defaultFileCharset");
            Folder folder = null;
            Part renderedPart = new MimeBodyPart();
            try {
                if (MailUtils.isOpenFolderRequired(this.message)) {
                    folder = this.message.getFolder();
                    if (! folder.isOpen()) {
                        folder.open(Folder.READ_ONLY);
                BufferedReader buf = new BufferedReader(
                        (charset != null && charset.length() > 0) ?
                        new InputStreamReader(part.getInputStream(), charset) :
                        new InputStreamReader(part.getInputStream()));
                StringBuffer stringbuf = new StringBuffer();
                String line = null;
                 * Microsoft Outlook Express 6 sends Byte Order Mark
                 * at the head of UTF-8 and UTF-7 stream. This BOM is displayed user
                 * page as ? mark, so skip the BOM.
                 * Note that charset is normalized by MimeUtility.javaCharset()
                 * before here.
                if (charset != null &&
                        (charset.equals("UTF8") || charset.equals("utf-7")) &&
                        buf != null && buf.markSupported()) {
                    buf.mark(10); // 10 byte is enough for read ahead limit.
                    int c = buf.read();
                    if (c != 0xfeff) { // Check BOM or not.
                        // Rewinding.
                        try {
                            buf.reset();
                        } catch (IOException e) {
                            // Buffer seems to be empty stream...
                            logger.debug("Reset exception: " + e.getMessage());
                    } else {
                        logger.debug("Skip BOM char: " + c);
                if (maxSize > 0) {
                    // It's hard to know exactly how much text to pass to the
                    // renderer, since if this is text/html, it may contain HTML
                    // tags that wouldn't be displayed on a WAP device, so just
                    // get start position + twice the max size.
                    int textSize = 2*maxSize;
                    if (state != null) {
                        textSize += state.getPosition();
                    while ((line = buf.readLine()) != null &&
                            stringbuf.length() < textSize) {
                        stringbuf.append(line).append("\n");
                } else {
                    while ((line = buf.readLine()) != null) {
                        stringbuf.append(line).append("\n");
                String content = stringbuf.toString();
                String contentType = null;
                if (part.isMimeType(MIME_DISPOSITION_NOTIFICATION)) {
                    contentType = MIME_TEXT_PLAIN;
                } else {
                    contentType = getNormalizedContentType(part).toString();
                Renderer renderer  = null;
                if (maxSize != 0) {
                    renderer = new TextRenderer(content, contentType,
                            setup, maxSize, state.getState());
                } else {
                    renderer =
                            new TextRenderer(content, contentType, setup);
                if (renderer.hasNext()) {
                    renderedPart.setText(renderer.next());
                    renderedPart.setHeader(HEADER_CONTENT_TYPE, contentType);
                state = new State(partIndex, renderer.toString());
                if (maxSize != 0) {
                    moreInCurrentPart = renderer.hasNext();
            } finally {
                if (folder != null && folder.isOpen()) {
                    MailUtils.closeFolder(folder);
            return renderedPart;
        }

  • 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);

  • Send multiple email attachments using FM SO_NEW_DOCUMENT_ATT_SEND_API1.How?

    Hi All,
    I have a requirement to send email to an external ID for which I am using FM SO_NEW_DOCUMENT_ATT_SEND_API1.Can anyone give a sample code to send multiple excel attachments using this function module.
    Points would be rewarded.
    Thanks
    Archana.

    Check the Thread,,
    Re: more than 1 attachements/sheets in SO_DOCUMENT_SEND_API1

  • 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 can I send multiple attachments using SO_DYNP_OBJECT_SEND?

    Hi,
    I hope someone can offer advice on my problem.
    My requirement is to allow users to select one or more documents from an ALV grid.  I am then required to send these documents to multiple users via email using function module SO_DYNP_OBJECT_SEND.
    I can successfully send one document as an attachment.  However, I can't seem to figure out how to send multiple documents as attachments using SO_DYNP_OBJECT_SEND.  Is this done in the packing list?
    Is there some way to tell the program where the 1st attachment ends and the 2nd attachment starts?
    My attachment content is in i_att_cont.
      CALL FUNCTION 'SO_DYNP_OBJECT_SEND'
        EXPORTING
          object_hd_change = l_title
          object_type      = 'RAW'
          raw_editor       = abap_true
          starting_at_x    = '5'
          starting_at_y    = '1'
          ending_at_x      = '120'
          ending_at_y      = '20'
          edit_title       = 'X'
          external_commit  = abap_true
        TABLES
          objcont          = i_objcont
          rec_tab          = i_rec_tab
          packing_list     = i_packing_list
          att_cont         = i_att_cont
          exclude_fcode    = i_exclude_fcode
        EXCEPTIONS
          object_not_sent  = 1
          owner_not_exist  = 2
          parameter_error  = 3
          OTHERS           = 4.
    If you require more information, please let me know.  I will be happy to provide it.
    Thanks.

    I finally found the solution.
    The trick is to ensure you put the correct values in the body_start, body_num and objlen fields of the packing list.
    Each additional attachment should start (body_start) at the end of the last attachment + 1.
    The value for body_num is equal to the number of lines in the attachment being added.
    And the objlen field is calculated by multiplying the number of lines in the attachent * 255.
    Static data
       gs_packing_list-file_ext = lv_ext.
       gs_packing_list-transf_bin = 'X'.
       gs_packing_list-objla = sy-langu.
       gs_packing_list-objtp = 'EXT'.
       gs_packing_list-objdes = lv_filename.
       gs_packing_list-objnam = 'Attachment'.
       gs_packing_list-head_start = 1.
       gs_packing_list-head_num = 1.
    Body Start
       CLEAR lv_count.
       DESCRIBE TABLE gt_temp_att_cont LINES lv_count.
       gs_packing_list-body_start = lv_count + 1.
    Body Num + Object Length
       CLEAR lv_count.
       DESCRIBE TABLE gt_att_cont LINES lv_count.
       gs_packing_list-body_num = lv_count.
       gs_packing_list-objlen = lv_count * 255.
       APPEND gs_packing_list TO gt_packing_list.
    Hopefully this helps some desperate soul in the future.

  • Error while using Javamail...pls help me...

    when i am using javamail for sending mail , i am getting error like,
    C:\jdk1.3\bin\mail>java MailSend
    [email protected] [email protected]
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException:
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at MailSend.Send(MailSend.java:56)
    at MailSend.main(MailSend.java:73)
    and i define properties like,
    mailProp.put("java", "java");
    where , "java" is my system name, and there is also mail server on my system. and my system is connected with proxy server..
    when i am trying
    mailProp.put("mail.smtp.host", "java");
    then i am getting same type of error...
    so, what is that ? pls help me to solve my error...

    Surely there's more information associated with that MessaginException than
    you've included here.
    Turn on session debugging and run your program again.
    http://java.sun.com/products/javamail/FAQ.html#debug

Maybe you are looking for