MimeMessage problem

I have the following problem using MimeMessage:
Shipment a mail, and when it receipt appears to me in body of the message the following thing:
Mime-Version: 1.0
Content-Type: multipart/mixed; boundary="----=_Part_1_1956022.1156444224755"
MSG_ID: 0
------=_Part_1_1956022.1156444224755
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
It seems that part of the header is mixed with the body of the message.
The big problem here is that the header lines you see up are not recognized like header lines because are mixed with the body.
Could anybody help me?

Email client Iam using tu recive the mail: yahoo and Outlook
In these two email clients you can hide or see the email header. When I set both
email clients to hide the headers the clients hide all except the Mime-Version, Content-Type,
Content-Transfer-Encoding...
So I understand that the email clients dont hide this things because it understand that they are not
part of the header of the message

Similar Messages

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

  • Problem sending email using javamail in servlet

    I try this code and make some changes of my own http://forums.sun.com/thread.jspa?threadID=695781.
    When i run the program the confirmtaion shows that the mail has been sent, but when i check in my inbox there's no the message. I'm using gmail and need to authenticate the username and password. I guess the error caused in the servlet.
    Here's the code for my servlet :
    import java.io.*;
    import java.util.Properties;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.mail.internet.*;
    import javax.mail.*;
    public class ServletEx extends HttpServlet {
       public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
          System.out.println("____emailservlet.doPost");
          response.setContentType("text/plain");
          PrintWriter out = response.getWriter();
          System.out.println("______________________________");
          out.println();
          String to = request.getParameter("to");
          System.out.println("____________________________to" + to);
          String subject = request.getParameter("subject");
          String msg = request.getParameter("msg");
          // construct an instance of EmailSender
          System.out.println("servlet_to" + to);
          send(username, to, subject, msg);
          //send("[email protected]", to, subject, msg);
          out.println("mail sent....");
            String username = "[email protected]";
            String password = "my_password";
            String smtp = "smtp.gmail.com";
            String port = "587";
       public void send(String username, String to, String subject, String msg) {
            Properties props = new Properties();
            props.put("mail.smtp.user", username);
            props.put("mail.smtp.host", smtp);
            props.put("mail.smtp.port", port);
            props.put("mail.smtp.starttls.enable","true"); // just in case, but not currently necessary, oddly enough
            props.put("mail.smtp.auth", "true");
            //props.put("mail.smtp.debug", "true");
            props.put("mail.smtp.socketFactory.port", 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 message = new MimeMessage(session);
                message.setText(msg);
                message.setSubject(subject);
                message.setFrom(new InternetAddress(username));
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                Transport.send(message);
            catch (Exception mex)
                mex.printStackTrace();
       public class SMTPAuthenticator extends javax.mail.Authenticator {
            public PasswordAuthentication getPasswordAuthentication(String username, String password)
                return new PasswordAuthentication(username, password);
    }Actually it's been a long time for me to develope this program, especially with the authenticate smtp. Any help would be very appreciated :)

    Accordingly to your stackTrace, I think that you miss some utility jar from Geronimo app. server.
    As you are using Application server that is J2EE compliant, so there is an own JavaMail implementation embeded and used by the Server. To fix this problem you have to find and add to your calsspath a jar-file that contains Base64EncoderStream.class

  • MimeMessage.reply() issue with MS Exchange Server 2007 Emails

    I have an application that retrieves emails from an MS Exchange Server 2003 mailbox. The data from each message is read, validated and conditionally loaded to a table. If the message doesn't pass validation, a rejection email is sent back to the sender with an error message and a copy of the email. (We're using Java 1.5. However, I test with both 1.5 and 1.6.)
    Also, if the message passes validation, positive notification is sent back to the sender.
    Both processes use the method: javax.mail.Message.reply()It's coded as:
    MimeMessage reply = (MimeMessage) message.reply(false);My organization is in the process of migrating to MS Exchange Server 2007. We've found that the reply() method no longer finds the sender method, thus unable to create a reply message. The error message we receive is:
    javax.mail.SendFailedException: No recipient addresses
         at javax.mail.Transport.send0(Transport.java:110)
         at javax.mail.Transport.send(Transport.java:80)
         at org.ccci.gms.datacollector.DataCollector.sendReply(DataCollector.java:514)
         at org.ccci.gms.datacollector.DataCollector.processMessages(DataCollector.java:162)
         at org.ccci.gms.datacollector.DataCollector.main(DataCollector.java:101)After creating the MimeMessage object from the reply() method, I printed out the email header detail from both 2003 and 2007 messages. You'll note from below that the "To" or recipient address is missing from Server 2007.
    MS Exchange 2003 works fine
    From: [email protected]
    To: [email protected]
    Subject: Re: Report
    In-Reply-To: <[email protected]>MS Exchange 2007 no longer works
    From: [email protected]
    Subject: Re: Reports
    In-Reply-To: <[email protected]>I know I could just use the "addRecipient()" method to get around this problem. I wanted to know if anyone has encountered this issue. Please share the resolution. Any suggestions will be greatly appreciated.
    Thanks,
    LaelW

    When the original message is accessed using IMAP, the reply method uses the information in the
    IMAP ENVELOPE to determine where to send the reply. It first looks for the Reply-To address
    in the ENVELOPE, then the From address.
    Interestingly, when not using IMAP, the getFrom method returns the Sender header if the From
    header is empty. The IMAP-specific code doesn't do that, although perhaps it should.
    It would be interesting to compare the ENVELOPE data from the protocol trace in the two cases.
    The ENVELOPE data will follow this syntax:
    envelope     = "(" env-date SP env-subject SP env-from SP
              env-sender SP env-reply-to SP env-to SP env-cc SP
              env-bcc SP env-in-reply-to SP env-message-id ")"
    So it's the first three address fields after the Subject that are relevant. If the From and Reply-To
    fields are NIL, but the Sender field has a valid address, let me know. I should probably fix the
    IMAP provider to fall back to the Sender field if the From field is missing.

  • Attachment Problem in JavaMail API

    Can anybody help me...
    when 'm trying to attach a file to a mailing aplication(sending attachment),
    an flurry of exceptions are occuring...
    'm using win98 and JDK1.4
    here is the code..can anybody provide a viable solution that works?
    thanks in advance
    * main1.java
    * Created on August 20, 2002, 2:55 PM
    * @author Shamik Ghosh
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.Properties;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    public class main1 extends javax.swing.JFrame implements ActionListener,ItemListener {
    JMenuBar mbar;
    JMenu file,other,help;
    JMenuItem open,save,read_mail;
    JFrame frame_f;
    FileReader fr;
    BufferedReader br;
    boolean check;
    String from_m,smtp_m,from_m1,smtp_m1,result,
    s1,s2,from_server,from_host,to_file,which_file,attach_text;
    File f;
    /** Creates new form main1 */
    public main1() {
    initComponents();
    setSize(550,500);
    setResizable(false);
    // ------------------------centering the display
    int width=550; // note that "width" & "height" are keywords and
    int height=500; // JAVA defined variables.
    Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
    int x=(screen.width-width)/2;
    int y=(screen.height-height)/2;
    setBounds(x,y,width,height);
    try{
    fr=new FileReader("address.txt");
    br=new BufferedReader(fr);
    String s;
    while((s=br.readLine()) !=null)
    {jComboBox1.addItem(s);}
    fr.close();
    }catch(Exception e){ System.out.println(e);}
    check_info();//calling the method to check the info
    //jTextField1.setText(from_m);
    //jTextField3.setText(smtp_m);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {//GEN-BEGIN:initComponents
    buttonGroup1 = new javax.swing.ButtonGroup();
    buttonGroup2 = new javax.swing.ButtonGroup();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jTextField3 = new javax.swing.JTextField();
    jComboBox1 = new javax.swing.JComboBox();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jLabel4 = new javax.swing.JLabel();
    jRadioButton3 = new javax.swing.JRadioButton();
    jRadioButton4 = new javax.swing.JRadioButton();
    jButton4 = new javax.swing.JButton();
    jButton6 = new javax.swing.JButton();
    jButton5 = new javax.swing.JButton();
    jTextField4 = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea2 = new javax.swing.JTextArea();
    jLabel6 = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();
    jLabel8 = new javax.swing.JLabel();
    jLabel9 = new javax.swing.JLabel();
    jLabel10 = new javax.swing.JLabel();
    //actionlisteners
    jButton1.addActionListener(this);
    jButton2.addActionListener(this);
    jButton3.addActionListener(this);
    jButton4.addActionListener(this);
    jButton5.addActionListener(this);
    jButton6.addActionListener(this);
    mbar=new JMenuBar();
    setJMenuBar(mbar);
    file=new JMenu("File");
    other=new JMenu("Other");
    help=new JMenu("Help");
    mbar.add(file);
    mbar.add(other);
    mbar.add(help);
    getContentPane().setLayout(null);
    setTitle("MailMan :Designed and Programmed by Shamik Ghosh");
    //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jLabel1.setText("From:");
    getContentPane().add(jLabel1);
    jLabel1.setBounds(30, 20, 32, 17);
    jLabel2.setText("To:");
    getContentPane().add(jLabel2);
    jLabel2.setBounds(30, 60, 17, 17);
    getContentPane().add(jTextField1);
    jTextField1.setBounds(110, 20, 240, 21);
    getContentPane().add(jTextField2);
    jTextField2.setBounds(110, 60, 240, 21);
    jLabel3.setText("Smtp Server:");
    getContentPane().add(jLabel3);
    jLabel3.setBounds(10, 100, 74, 17);
    getContentPane().add(jTextField3);
    jTextField3.setBounds(110, 100, 240, 21);
    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] {  }));
    jComboBox1.setToolTipText("Mail Addresses");
    jComboBox1.setAutoscrolls(true);
    jComboBox1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jComboBox1ActionPerformed(evt);
    getContentPane().add(jComboBox1);
    jComboBox1.setBounds(110, 150, 240, 20);
    jComboBox1.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    jButton1.setToolTipText("Send the message you have typed");
    jButton1.setMnemonic('m');
    jButton1.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    jButton1.setText("Send Mail");
    getContentPane().add(jButton1);
    jButton1.setBounds(370, 300, 160, 25);
    //jButton2.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 12));
    jButton2.setText("Save Info");
    jButton2.setToolTipText("Save Settings for more mails");
    jButton2.setMnemonic('I');
    getContentPane().add(jButton2);
    jButton2.setBounds(370, 340, 160, 25);
    jButton3.setText("Clear ");
    jButton3.setMnemonic('C');
    jButton3.setToolTipText("Clear all text");
    getContentPane().add(jButton3);
    jButton3.setBounds(370, 380, 160, 27);
    jLabel4.setText("Your Contact Addresses");
    jLabel4.setFont(new java.awt.Font("Arial Narrow", 0, 12));
    getContentPane().add(jLabel4);
    jLabel4.setBounds(110, 130, 200, 15);
    jRadioButton3.setText("Use Log File");
    jRadioButton3.setMnemonic('L');
    getContentPane().add(jRadioButton3);
    jRadioButton3.setBounds(260, 310, 90, 25);
    jRadioButton4.setText("No Log File");
    //jRadioButton4.setMnemonic('N');
    //getContentPane().add(jRadioButton4);
    //jRadioButton4.setBounds(260, 340, 86, 25);
    jButton4.setText("Undo Info");
    jButton4.setMnemonic('U');
    jButton4.setToolTipText("Undo settings");
    getContentPane().add(jButton4);
    jButton4.setBounds(260, 380, 87, 27);
    getContentPane().add(jTextField4);
    jTextField4.setBounds(20, 380, 210, 21);
    jLabel5.setText("Attachment");
    jLabel5.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    getContentPane().add(jLabel5);
    jLabel5.setBounds(70, 360, 70, 15);
    jButton5.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    jButton5.setText("Browse");
    jButton5.setMnemonic('B');
    jButton5.setToolTipText("Browse files for Attachment");
    getContentPane().add(jButton5);
    jButton5.setBounds(150, 350, 80, 25);
    jButton6.setText("Attach & Send");
    jButton6.setMnemonic('A');
    jButton6.setToolTipText("Attach File & Send Mail");
    getContentPane().add(jButton6);
    jButton6.setBounds(260, 340, 86, 25);
    jScrollPane1.setViewportView(jTextArea1);
    getContentPane().add(jScrollPane1);
    jScrollPane1.setBounds(370, 20, 160, 270);
    jLabel10.setText("Type your mail:");
    jLabel10.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    getContentPane().add(jLabel10);
    jLabel10.setBounds(370, 5, 125, 10);
    jScrollPane2.setViewportView(jTextArea2);
    getContentPane().add(jScrollPane2);
    jScrollPane2.setBounds(20, 200, 340, 90);
    jLabel6.setText("(your ISP smtp)");
    jLabel6.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel6);
    jLabel6.setBounds(10, 120, 70, 12);
    jLabel7.setText("porgrammed and designed by : Shamik Ghosh");
    jLabel7.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel7);
    jLabel7.setBounds(260, 410, 160, 12);
    jLabel8.setText("[email protected]");
    jLabel8.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel8);
    jLabel8.setBounds(420, 410, 80, 12);
    jLabel9.setText("Msg.for the Mail Sent:");
    jLabel9.setForeground(java.awt.Color.black);
    jLabel9.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel9);
    jLabel9.setBounds(20, 180, 80, 12);
    file.add(open=new JMenuItem("Open"));
    open.setAccelerator(KeyStroke.getKeyStroke('O',Event.CTRL_MASK,true));
    file.addSeparator();
    file.add(save=new JMenuItem("Save"));
    save.setAccelerator(KeyStroke.getKeyStroke('S',Event.CTRL_MASK,true));
    file.addSeparator();
    other.add(read_mail=new JMenuItem("Add Address"));
    read_mail.setAccelerator(KeyStroke.getKeyStroke('A',Event.CTRL_MASK,true));
    other.addSeparator();
    //adding actionListener to menuitems
    open.addActionListener(this);
    save.addActionListener(this);
    read_mail.addActionListener(this);
    jComboBox1.addItemListener(this);
    pack();
    }//GEN-END:initComponents
    public void itemStateChanged(ItemEvent ie)
    String add_list;
    add_list=String.valueOf(jComboBox1.getSelectedItem());
    jTextField2.setText(add_list);
    } // for item event source
    public void actionPerformed(ActionEvent ae)
    if(ae.getSource()==jButton1)
    if(ae.getSource()==jButton1) {
    SwingUtilities.invokeLater(new Runnable()
    {  public void run()
    sendMail();
    if(ae.getSource()==jButton2) //save info
    from_m =jTextField1.getText();
    smtp_m =jTextField3.getText();
    from_m1 =from_m+"\n";
    smtp_m1 =jTextField3.getText();
    result =from_m1+smtp_m1;
    try{
    byte buf[]=result.getBytes();
    OutputStream fo=new FileOutputStream("info.txt");
    for(int i=0;i<buf.length; i++ )
    fo.write(buf);
    fo.close();
    }catch(Exception e){ System.out.println(e);}
    jTextField1.setEditable(false);
    jTextField3.setEditable(false);
    if(ae.getSource()==jButton3) //clear
    jTextArea1.setText(" ");
    jTextArea2.setText(" ");
    if(ae.getSource()==jButton4)//undo info
    jTextField1.setEditable(true);
    jTextField3.setEditable(true);
    if(ae.getSource()==jButton5)//browse for attachment
    try {
    FileDialog file = new FileDialog (main1.this, "Load File", FileDialog.LOAD);
    file.setFile ("*.*"); // Set initial filename filter
    file.show(); // Blocks
    String curFile;
    if ((curFile = file.getFile()) != null) {
    String filename = file.getDirectory() + curFile;
    char[] data;
    setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    f = new File (filename);
    try {
    System.out.println("INSIDE TRY");
    FileReader fin = new FileReader (f);
    int filesize = (int)f.length();
    data = new char[filesize];
    fin.read (data, 0, filesize);
    setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    } catch (Exception exc) {}
    jTextField4.setText(filename);
    } catch(Exception e){}
    if(ae.getSource()==jButton6)//send attachment & Mail
    try{
    sendmail2();
    }catch(Exception e){}
    if(ae.getSource()==open)//menu open
    if(ae.getSource()==save)//menu save
    if(ae.getSource()==read_mail)//menu read_mail
    address_add();
    } //actionperformed
    public void sendmail2()
    try {
    //which_file,attach_text
    from_server=jTextField3.getText();
    from_host=jTextField1.getText();
    to_file=jTextField2.getText();
    which_file=jTextField4.getText();
    attach_text=jTextArea1.getText();
    //getting system property
    Properties props=System.getProperties();
    //setup mail server
    props.put("mail.smtp.host",from_server);
    //get session
    Session session=Session.getInstance(props,null);
    // Define message
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from_host));
    message.addRecipient(Message.RecipientType.TO,
    new InternetAddress(to_file));
    message.setSubject("Hello JavaMail Attachment");
    //define message part
    BodyPart messageBodyPart=new MimeBodyPart();
    // Fill the message
    messageBodyPart.setText(attach_text);
    // Create a Multipart
    Multipart multipart = new MimeMultipart();
    // Add part one
    multipart.addBodyPart(messageBodyPart);
    //attaching**********************************secon Part Attachment
    //creating second body part
    messageBodyPart=new MimeBodyPart();
    DataSource source=new FileDataSource(which_file); //was filename
    //setting data handler to the attachment
    messageBodyPart.setDataHandler(new DataHandler(source));
    //setting the filename
    messageBodyPart.setFileName(which_file);
    //adding part two
    multipart.addBodyPart(messageBodyPart);
    //put parts in the message
    message.setContent(multipart);
    //Sending msg
    Transport.send(message);
    }catch(Exception e){}
    } //sendmail2
    public void address_add()
    addr=jTextField2.getText();
    str_addr=addr+"\n";
    //jComboBox1.addItem(" ");
    jComboBox1.addItem(addr);
    System.out.println("INSIDE WRITING METHOD");
    try{
    byte buf[]=str_addr.getBytes();
    OutputStream f0=new FileOutputStream("address.txt",true);
    for(int i=0;i<buf.length; i++ )
    f0.write(buf[i]);
    f0.close();
    }catch(Exception e){ System.out.println(e);}
    public void check_info()
    try{
    fr=new FileReader("info.txt");
    br=new BufferedReader(fr);
    while((s1=br.readLine()) !=null && (s2=br.readLine()) !=null)
    jTextField1.setText(s1);
    jTextField3.setText(s2);
    break;
    fr.close();
    }catch(Exception e){ System.out.println(e);}
    public void sendMail()
    {  try
    Socket s = new Socket(jTextField3.getText(), 25);
    out = new PrintWriter(s.getOutputStream());
    in = new BufferedReader(new
    InputStreamReader(s.getInputStream()));
    String hostName
    = InetAddress.getLocalHost().getHostName();
    send(null);
    send("Host " + hostName);
    send("Mail FROM: " + jTextField1.getText());
    send("Rcpt TO: " + jTextField2.getText());
    send("Data");
    out.println(jTextArea1.getText());
    send(".");
    s.close();
    catch (IOException exception)
    {  jTextArea2.append("Error: " + exception);
    String err="Message cannot be sent!"+"\n"
    +"Please verify the setting(s)."+
    "\n"+"Else there may be a NetWork Problem."+
    "\n"+"Please verify and Try Again.";
    JOptionPane.showMessageDialog(frame_f,err,"Message Transmission Failure",JOptionPane.ERROR_MESSAGE);
    public void send(String s) throws IOException
    {  if (s != null)
    {  jTextArea2.append(s + "\n");
    out.println(s);
    out.flush();
    String line;
    if ((line = in.readLine()) != null)
    jTextArea2.append(line + "\n");
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
    // Add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
    System.exit(0);
    }//GEN-LAST:event_exitForm
    * @param args the command line arguments
    public static void main(String args[]) {
    new main1().show();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JRadioButton jRadioButton4;
    private javax.swing.JButton jButton4;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabel10;
    private BufferedReader in;
    private PrintWriter out;
    private String addr,str_addr;
    // End of variables declaration//GEN-END:variables

    Hi I have this problem which I believe you can help me resolve:
    In my code, there are two lines:
    message.setContent(messageBody, "text/html"); // this sets body of message
    message.setContent(bodyPartObject); // this attaches a file
    but it turns out that the second "setContent" statement over-writes the first one, so that I get no message in the body of the mail.
    What can I do about it, shamik1? Thanks!

  • Problem in sending mails to multiple persons

    Hi,
    I have a problem in sending mails to multiple people....
    My mail is using the local smtp server...The mail is to be send to multiple addresses in to and cc.
    for e.g the to address will have --> [email protected];[email protected]
    cc address will have --> [email protected];[email protected]
    How do this i.e set multiple to and cc address...
    My function that sends mail from my ejb looks like this...
    // create some properties and get the default Session
         Properties props = new Properties();
         props.put("mail.smtp.host", host);
         Session session = Session.getDefaultInstance(props, null);
         try{
         Message msg = new MimeMessage(session);
         msg.setFrom(new InternetAddress(from));
    //I HAVE TO SET MULTIPLE "TO" ADDRESSES HERE INSTEAD OF JUST 1
         InternetAddress[] address = {new InternetAddress(to)};
         msg.setRecipients(Message.RecipientType.TO, address);
    //I HAVE TO SET MULTIPLE "CC" ADDRESSES HERE INSTEAD OF JUST 1
    InternetAddress[] addresscc = {new InternetAddress(cc)};
         msg.setRecipients(Message.RecipientType.CC, addresscc);
         msg.setSubject(msgSubj);
         msg.setSentDate(new java.util.Date());
         msg.setText(msgText);
         Transport.send(msg);
         }catch (MessagingException ex) {
    System.out.println("\nException handling in javaMail.java :" + ex);
    Please help me out with a solution!!!Thanks in advance.
    Thanks
    Rahul

    Hi all,
    Got the solution...
    We have to use addRecipients method of the Message class to add as many receipts we want to set.
    example: Message.addRecipients(type,address).
    Thanks
    Rahul

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

  • Problem in sending images

    Hi All,
    I have a problem in sending HTML mail with images.I am able to get the image in my mail if i place the image part and the html part in two different tables I am able to get the image along with the html message but if i use the following code i.e using single table i am not able to get the image someone plase help me to get this done and tell me where am i going wrong?
    Properties props = System.getProperties();
                    props.put("mail.smtp.host", smtpServer);
                    Session session = Session.getDefaultInstance(props, null);
                     Message message = new MimeMessage(session);
                   message.setFrom(new InternetAddress(from));
                    message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to, false));
                     message.setSubject(subject);
                   message.setSentDate(new Date());
                    MimeBodyPart messageBodyPart = new MimeBodyPart();
              MimeBodyPart messageBodyPart1 = new MimeBodyPart();
              MimeBodyPart messageBodyPart2 = new MimeBodyPart();
    StringBuffer msgStrBuf = new StringBuffer();
    msgStrBuf.append("<html><head></head> <body><table  width=\"640\" align=\"center\"  height=\"293\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"#D3D3D3\" ><tr><td><img src=\"cid1:image1\" width=\"640\" height=\"92\"></td></tr>");
    DataSource fds1 = new FileDataSource("webimages\\sampleimage.jpg");
    messageBodyPart.setDataHandler(new DataHandler(fds1));
    messageBodyPart.setHeader("Content-ID1","<image1>");
    String headerbody = "";
    msgStrBuf.delete(0,msgStrBuf.length());
    msgStrBuf.append("<tr><td width=\"640\" align=\"center\"   bgcolor=\"#E6E6E6\" height=\"50\" valign=\"top\"><font size=\"2\" color=\"#4C4C4C\" face=\" Arial,Verdana, Helvetica, sans-serif\">����Dear "+locUserName+","+"<br><br>����"+"Here is the updated status report on your project.</font></td></tr>"+"  <tr> <td bgcolor=\"#E6E6E6\" height=\"100\" align=\"center\" valign=\"middle\">  <table width=\"95%\" height=\"100\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"4C4C4C\" >" +"<tr> <td width=\"200\" align=\"left\" valign=\"middle\"><strong><font  size=\"2\" face=\" Arial,Verdana, Helvetica, sans-serif\" color=\"#FFFFFF\">��PROJECT:</font></strong></td><td><font  size=\"2\" face=\" Arial,Verdana, Helvetica, sans-serif\" color=\"#FFFFFF\"><strong>"+getProjectName+"</strong></font></td></tr>"+"   <tr> <td  width=\"200\" align=\"left\" valign=\"middle\"><font  size=\"2\" face=\" Arial,Verdana, Helvetica, sans-serif\" color=\"#FFFFFF\"><strong>��LAST UPDATE:</strong></font></td><td><font  size=\"2\" face=\" Arial,Verdana, Helvetica, sans-serif\" color=\"#FFFFFF\"><strong>"+concatTime+"</strong></font></td></tr></tr></table></td></tr> "  );
    msgStrBuf.append("<tr> <td  bgcolor=\"#E6E6E6\" height=\"50\" valign=\"middle\"><font size=\"2\" color=\"#4C4C4C\" face=\" Arial,Verdana, Helvetica, sans-serif\">����" +"In case you have any questions, please send an email to <a href=\"mailto: </a>. Our customer <br>����service representative will contact you to address any  concerns. ");
    msgStrBuf.append("<br><br>����Thank You,<br> ���.</font></td></tr>");
    msgStrBuf.append("<tr><td  bgcolor=\"#E6E6E6\" height=\"100\" valign=\"top\"> <br><hr><font color=\"#666666\" size=\"-6\" face=\" Arial,Verdana, Helvetica, sans-serif\">����This is an automatically generated email. Please do not reply to this. If you need further information, contact the email address <br>����given above.<br>����If you wish to change your contact email address, please log in to follow the link and modify your<br>����preferences. You can also change the frequency of email updates in the project settings link.</font></td></tr>");
    msgStrBuf.append("</table></body></html>");
    headerbody = msgStrBuf.toString();
    messageBodyPart1.setContent(headerbody,"text/html");
    // Part two is attachment
    String mailingFileId = "";
    if(locGroupClass.equals("2"))
    mailingFileId = "XL Data/"+getProjectID+".xls";
    else{
    mailingFileId = "GPXL Data/"+getProjectName+".xls";
    System.out.println("mailingFileId :"+mailingFileId);
    System.out.println("locGroupClass :"+locGroupClass);
    String mailingFileNAme = getProjectName+".xls";
    DataSource source = new FileDataSource(mailingFileId);
    messageBodyPart2.setDataHandler(new DataHandler(source));
    messageBodyPart2.setFileName( mailingFileNAme);
    multipart.addBodyPart(messageBodyPart);
    multipart.addBodyPart(messageBodyPart1);
    multipart.addBodyPart(messageBodyPart2);
    // Put parts in message
              message.setContent(multipart);
                       Transport.send(message);
                    System.out.println("Message sent OK.");
                  } catch (Exception ex)
                              ex.printStackTrace();
                        }Message was edited by:
    rameshr

    messageBodyPart.setHeader("Content-ID1","<image1>");The name of the header is "Content-ID", not "Content-ID1".
    Of course, if you used the setContentID method on MimeBodyPart,
    the compiler would find this error for you.

  • Problem in sending mail for a pop3 account using transport.send(msg)

    hi,
    i am having problem in not able to send mail for a pop3 account ...
    I have written an email gateway which listens to my pop3 account...on email arrival it listens nd extract the contents and send it as an sms msg...upon failure it needs to deliver the mail to sender id.I am using quartz to listen.
    i am using jboss for server and java mail api.
    here is my code
    MimeMessage mimemsg = new MimeMessage(session);
                                                           mimemsg.setFrom();
                                                           mimemsg.setRecipients(Message.RecipientType.TO, to);
                                                           mimemsg.setSubject(subject);
                                                           mimemsg.setText(parsedText);
                                                           mimemsg.setSentDate(new Date());
                                                           mimemsg.setContent(strBuff.toString(), "text/html");
                                                           System.out
                                                                                    .println("Before sending mail");
                                                           Transport.send(m);
                                                                System.out.println("message sent successfully");
    excepition i am getting is :
    2008-09-12 11:45:11,140 INFO [STDOUT] Before sending mail
    2008-09-12 11:45:11,140 ERROR [STDERR] javax.mail.IllegalWriteException: POP3 messages are read-only
    2008-09-12 11:45:11,140 ERROR [STDERR]      at com.sun.mail.pop3.POP3Message.saveChanges(POP3Message.java:438)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at javax.mail.Transport.send(Transport.java:97)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at com.openstream.emailgateway.sources.ListenEmailGateway.execute(ListenEmailGateway.java:422)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at sun.reflect.GeneratedMethodAccessor89.invoke(Unknown Source)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at java.lang.reflect.Method.invoke(Method.java:585)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.invocation.Invocation.performCall(Invocation.java:359)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.ejb.MessageDrivenContainer$ContainerInterceptor.invoke(MessageDrivenContainer.java:495)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invoke(CachedConnectionInterceptor.java:158)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.ejb.plugins.MessageDrivenInstanceInterceptor.invoke(MessageDrivenInstanceInterceptor.java:116)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.ejb.plugins.CallValidationInterceptor.invoke(CallValidationInterceptor.java:63)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:121)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxInterceptorCMT.java:350)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:181)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.ejb.plugins.RunAsSecurityInterceptor.invoke(RunAsSecurityInterceptor.java:109)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:205)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invoke(ProxyFactoryFinderInterceptor.java:138)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.ejb.MessageDrivenContainer.internalInvoke(MessageDrivenContainer.java:402)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.ejb.Container.invoke(Container.java:960)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at sun.reflect.GeneratedMethodAccessor88.invoke(Unknown Source)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at java.lang.reflect.Method.invoke(Method.java:585)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
    2008-09-12 11:45:11,140 ERROR [STDERR]      at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.invocation.local.LocalInvoker$MBeanServerAction.invoke(LocalInvoker.java:169)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.invocation.local.LocalInvoker.invoke(LocalInvoker.java:118)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.invocation.InvokerInterceptor.invokeLocal(InvokerInterceptor.java:209)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.invocation.InvokerInterceptor.invoke(InvokerInterceptor.java:195)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.proxy.TransactionInterceptor.invoke(TransactionInterceptor.java:61)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.ejb.plugins.inflow.MessageEndpointInterceptor.delivery(MessageEndpointInterceptor.java:263)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.ejb.plugins.inflow.MessageEndpointInterceptor.invoke(MessageEndpointInterceptor.java:140)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.proxy.ClientMethodInterceptor.invoke(ClientMethodInterceptor.java:74)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.proxy.ClientContainer.invoke(ClientContainer.java:100)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at $Proxy73.execute(Unknown Source)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.jboss.resource.adapter.quartz.inflow.QuartzJob.execute(QuartzJob.java:57)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.quartz.core.JobRunShell.run(JobRunShell.java:203)
    2008-09-12 11:45:11,171 ERROR [STDERR]      at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:520)
    2008-09-12 11:45:11,171 INFO [STDOUT] USer flag ..[Ljava.lang.String;@115c6cb                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    as i am writing the message failure details to a template...
         //on failure to send messages , reply to the sender about the failure
                                                                strBuff= tempDetail.writeToTemplate(smsmsg);     
    is that bcoz i am getting an exception

  • Problem in sending a attachnment or photo using javamailapi

    Hello Sir,
    My program is perfectly when i'm sending simply a text message but problem is arised when i want to send an attachment.
    MY Code is
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    import java.io.*;
    import javax.activation.*;
    import java.util.Properties;
    public class SendAtthachment
    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_AUTH_USER = "[email protected]";
    private static final String SMTP_AUTH_PWD = "hindustan";
    private static final String fname= "my.jpg";
    private static final String emailMsgTxt = "motion is detected,some one is in your home";
    private static final String emailSubjectTxt = "motion";
    private static final String emailFromAddress = "[email protected]";
    private static final String[] emailList = {"[email protected]", "[email protected]"};
    public static void main(String args[]) throws Exception
    SendAtthachment smtpMailSender = new SendAtthachment();
    smtpMailSender.postMail( fname,emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
    System.out.println("Sucessfully Sent mail to All Users");
    public void postMail( String filename,String recipients[ ], String subject, String message , String from) throws MessagingException
    boolean debug = false;
    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "587") ;
    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);
    session.setDebug(debug);
    Message msg = new MimeMessage(session);
    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);
    msg.setSubject(subject);
    BodyPart msgBP = new MimeBodyPart();
    msg.setText("Take a look at this");
    Multipart mpart = new MimeMultipart();
    mpart.addBodyPart(msgBP);
    msgBP = new MimeBodyPart();
    DataSource src = new FileDataSource(filename);
    msgBP.setDataHandler(new DataHandler(src));
    msgBP.setFileName(filename);
    mpart.addBodyPart(msgBP);
    msg.setContent(message, "text/plain");
    msg.setContent(mpart);
    Transport.send(msg);
    private class SMTPAuthenticator extends javax.mail.Authenticator
    public PasswordAuthentication getPasswordAuthentication()
    String username = SMTP_AUTH_USER;
    String password = SMTP_AUTH_PWD;
    return new PasswordAuthentication(username, password);
    And this exception arised at run time-
    E:\gaurav\study material\motion detector\Motion Detector>java SendAtthachment
    Exception in thread "main" javax.mail.MessagingException: IOException while send
    ing message;
    nested exception is:
    java.io.IOException: No content
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:676)
    at javax.mail.Transport.send0(Transport.java:189)
    at javax.mail.Transport.send(Transport.java:118)
    at SendAtthachment.postMail(SendAtthachment.java:76)
    at SendAtthachment.main(SendAtthachment.java:25)
    Caused by: java.io.IOException: No content
    at javax.mail.internet.MimePartDataSource.getInputStream(MimePartDataSou
    rce.java:119)
    at javax.activation.DataHandler.writeTo(DataHandler.java:318)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1403)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:874)
    at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:444)
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:10
    2)
    at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:89
    7)
    at javax.activation.DataHandler.writeTo(DataHandler.java:330)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1403)
    at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1745)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:636)
    ... 4 more
    E:\gaurav\study material\motion detector\Motion Detector>

    You're creating a body part for the attachment, but you also need to
    create a body part for the main text of your message. See the sendfile.java
    demo program included with JavaMail for an example.

  • How to solve this problem javax.mail.AuthenticationFailedException

    i was used in this progrm my labtop means working correctly but instead of labtop i am using the desktop means following error is occuered can any one tell to me how to solve this problem.The erroe is **javax.mail.AuthenticationFailedException**
    The coding is as followes
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    public class Main
    String d_email = "[email protected]",
    d_password = "inst9",
    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);
    }

    yes that not a my password ...but the following erroer is occured ...
    run-main:
    javax.mail.AuthenticationFailedException
    at javax.mail.Service.connect(Service.java:319)
    at javax.mail.Service.connect(Service.java:169)
    at javax.mail.Service.connect(Service.java:118)
    at javax.mail.Transport.send0(Transport.java:188)
    at javax.mail.Transport.send(Transport.java:118)
    at Main.<init>(Main.java:41)
    at Main.main(Main.java:51)
    BUILD SUCCESSFUL (total time: 3 seconds)
    I am using the netbeand 5.5

  • Problem in sending mail using java mail api

    This is the pogram I am using as of now to send a mail to yahoo id.
    import javax.mail.*;
    import javax.mail.internet.*;
    public class SendingMail2
    public SendingMail2()
    try
    String from = "ravikiran_sunrays";
    String to = "[email protected]";
    String subject = "the subject u wanna send ";
    String cc="[email protected]";
    String bcc="[email protected]";
    String text="the matter that u wanna send ";
    java.util.Properties prop = System.getProperties();
    prop.put("mail.smtp.host","mail.yahoo.com");
    //prop.put("http.proxyHost",System.getProperty("http.proxyHost"));
    //prop.put("http.proxyPort","8080");
    //prop.put("http.proxyPort",System.getProperty("http.proxyPort"));
    //prop.put("http.proxyHost","172.19.48.201");
    //System.getProperties().setProperty("http.proxyPort","8080");
    //System.getProperties().setProperty("http.proxyHost","172.19.48.201");
    Session ses = Session.getInstance(prop,null);
    MimeMessage message = new MimeMessage(ses);
    try
    Address fromAddress = new InternetAddress(from);
    message.setFrom(fromAddress);
    message.setSubject(subject);
    Address[] toAddress = InternetAddress.parse(to);
    Address[] cc_address=InternetAddress.parse(cc);
    Address[] bcc_address=InternetAddress.parse(bcc);
    message.setRecipients(Message.RecipientType.TO,toAddress);
    message.setRecipients(Message.RecipientType.CC,cc_address);
    message.setRecipients(Message.RecipientType.BCC,bcc_address);
    message.setSentDate(new java.util.Date());
    message.setText(text);
    Transport.send(message);
    System.out.println("Mail Successfully Sent");
    catch(Exception e)
    System.out.println("Problem " + e);
    catch(Exception e)
    System.out.println("Problem " + e);
    public static void main(String[] args)
    SendingMail2 sendingMail2 = new SendingMail2();
    This is the exception I am getting when I try 2 execute that program.
    avax.mail.SendFailedException: Sending failed;
    nested exception is:
         javax.mail.MessagingException: Unknown SMTP host: mail.yahoo.com;
    nested exception is:
         java.net.UnknownHostException: mail.yahoo.com

    listen buddy
    this is a class i made it is easy to understand it sends mails and check inbox just adduser from telnet with remote manager in james create the three accounts i am using and then use this class and its methods
    also the next class that contains the mails test my class and what i am saying
    import java.io.*;
    import java.util.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    public class MailClient
    extends Authenticator
    public static final int SHOW_MESSAGES = 1;
    public static final int CLEAR_MESSAGES = 2;
    public static final int SHOW_AND_CLEAR =
    SHOW_MESSAGES + CLEAR_MESSAGES;
    protected String from;
    protected Session session;
    protected PasswordAuthentication authentication;
    public MailClient(String user, String host)
    this(user, host, false);
    public MailClient(String user, String host, boolean debug)
    from = user + '@' + host;
    authentication = new PasswordAuthentication(user, user);
    Properties props = new Properties();
    props.put("mail.user", user);
    props.put("mail.host", host);
    props.put("mail.debug", debug ? "true" : "false");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    session = Session.getInstance(props, this);
    public PasswordAuthentication getPasswordAuthentication()
    return authentication;
    public void sendMessage(
    String to, String subject, String content)
    throws MessagingException
    System.out.println("SENDING message from " + from + " to " + to);
    System.out.println();
    MimeMessage msg = new MimeMessage(session);
    msg.addRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject);
    msg.setText(content);
    Transport.send(msg);
    public void checkInbox(int mode)
    throws MessagingException, IOException
    if (mode == 0) return;
    boolean show = (mode & SHOW_MESSAGES) > 0;
    boolean clear = (mode & CLEAR_MESSAGES) > 0;
    String action =
    (show ? "Show" : "") +
    (show && clear ? " and " : "") +
    (clear ? "Clear" : "");
    System.out.println(action + " INBOX for " + from);
    Store store = session.getStore();
    store.connect();
    Folder root = store.getDefaultFolder();
    Folder inbox = root.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Message[] msgs = inbox.getMessages();
    if (msgs.length == 0 && show)
    System.out.println("No messages in inbox");
    for (int i = 0; i < msgs.length; i++)
    MimeMessage msg = (MimeMessage)msgs;
    if (show)
    System.out.println(" From: " + msg.getFrom()[0]);
    System.out.println(" Subject: " + msg.getSubject());
    System.out.println(" Content: " + msg.getContent());
    if (clear)
    msg.setFlag(Flags.Flag.DELETED, true);
    inbox.close(true);
    store.close();
    System.out.println();
    ====================================
    testing this class
    =======================================
    public class JamesConfigTest
    public static void main(String[] args)
    throws Exception
    // CREATE CLIENT INSTANCES
    MailClient redClient = new MailClient("red", "localhost");
    MailClient greenClient = new MailClient("green", "localhost");
    MailClient blueClient = new MailClient("blue", "localhost");
    // CLEAR EVERYBODY'S INBOX
    redClient.checkInbox(MailClient.CLEAR_MESSAGES);
    greenClient.checkInbox(MailClient.CLEAR_MESSAGES);
    blueClient.checkInbox(MailClient.CLEAR_MESSAGES);
    Thread.sleep(500); // Let the server catch up
    // SEND A COUPLE OF MESSAGES TO BLUE (FROM RED AND GREEN)
    redClient.sendMessage(
    "blue@localhost",
    "Testing blue from red",
    "This is a test message");
    greenClient.sendMessage(
    "blue@localhost",
    "Testing blue from green",
    "This is a test message");
    Thread.sleep(500); // Let the server catch up
    // LIST MESSAGES FOR BLUE (EXPECT MESSAGES FROM RED AND GREEN)
    blueClient.checkInbox(MailClient.SHOW_AND_CLEAR);
    =======================================================
    it suppose to print this
    Clear INBOX for red@localhost
    Clear INBOX for green@localhost
    Clear INBOX for blue@localhost
    SENDING message from red@localhost to blue@localhost
    SENDING message from green@localhost to blue@localhost
    Show and Clear INBOX for blue@localhost
    From: green@localhost
    Subject: Testing blue from green
    Content: This is a test message
    From: red@localhost
    Subject: Testing blue from red
    Content: This is a test message
    thanks a lot
    but i need ur help plzzzzzzzzzzzz
    i can create account from telnet
    but how i can create a new account from java .. a jsp page that i made to create a new account on the server
    plzzzzzzzz help me
    bye

  • Problem Sending attachments with JavaMail API

    Hi,
    I am able to succesfully able to send the attachment but the body message is not going with it. If i dont send the attachment then the email body goes properly. i can't understand what the problem is . please help.
    import java.util.*;
    import java.io.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    import com.sun.mail.smtp.SMTPMessage;
    public class Emailer
         String emailSubject = null;
         String emailBody = null;
        String smtphost = null;
         String ccAddr = null;
         String file = "C:\\trainee\\eclipse_lg.gif";
         Vector vecToAddr = null;
         Vector vecCCAddr = null;
         Address fromAddr = null;
      public Emailer(Hashtable hashConfigParam) throws Exception
            smtphost = (String)hashConfigParam.get("host");
            ccAddr = (String)hashConfigParam.get("ccAddr");
            vecToAddr = new Vector();
            vecCCAddr = new Vector();
      public Boolean setFromAddr(String fromEmailAddr)
              try
                   fromAddr = new InternetAddress (fromEmailAddr);
                   //if(true)
                   //throw new IOException();
              catch (Exception e)
                   return null;
         return new Boolean(true);
      public Boolean setToAddr(String toEmailAddr)
              try
                   for(int j=0; j< vecToAddr.size();j++)
                        if(((String)vecToAddr.get(j)).equals(toEmailAddr))
                             return new Boolean(false);
                   vecToAddr.add(toEmailAddr);
                   //if(true)
                   //throw new IOException();
              catch (Exception e)
                   return null;
                   return new Boolean(true);     
         public Boolean setCCAddr(String ccEmailAddr)
              try
                   for(int j=0; j< vecCCAddr.size();j++)
                        if(((String)vecCCAddr.get(j)).equals(ccEmailAddr) && ((String)vecCCAddr.get(j)).equals(ccAddr))
                             return new Boolean(false);
                   vecCCAddr.add(ccEmailAddr);
                   vecCCAddr.add(ccAddr);
                   //if(true)
                   //throw new IOException();
              catch (Exception e)
                   //System.out.println(e.getClass().getName());
                   return null;
              return new Boolean(true);               
         public Boolean setEmailSubject(String subject)
              try
                   emailSubject = subject;
                   if(emailSubject.equals(null))
                        return new Boolean(false);
                   else
                        return new Boolean(true);
              catch (Exception e)
                   return null;
              //return new Boolean(false);
         public Boolean setEmailBody(String body)
              try
                   emailBody = body;
                   if(emailBody.equals(""))
                        return new Boolean(false);
                   else
                        return new Boolean(true);
              catch (Exception e)
                   return null;
              //return new Boolean(false);
      public void sendEmail()
           try
                Properties eMailConfigProps = null;
                eMailConfigProps = System.getProperties();
                eMailConfigProps.put("mail.smtp.host", smtphost);
                Session session = Session.getInstance(eMailConfigProps, null);
                MimeMessage message = new MimeMessage(session);
                   try
                     message.setFrom(fromAddr);
                      for(int i=0; i< vecToAddr.size(); i++)
                         message.addRecipient(Message.RecipientType.TO,new InternetAddress((String)vecToAddr.get(i)));
                         for(int i=0; i< vecCCAddr.size(); i++)
                          message.addRecipient(Message.RecipientType.CC,new InternetAddress((String)vecCCAddr.get(i)));
                      message.setSubject(emailSubject);
                      //message.setText(emailBody);
                       BodyPart messageBodyPart = new MimeBodyPart();
                        messageBodyPart.setText(emailBody);
                        Multipart multipart = new MimeMultipart();
                        DataSource source = new FileDataSource(file);
                        messageBodyPart.setDataHandler(new DataHandler(source));
                        messageBodyPart.setFileName(file);
                        multipart.addBodyPart(messageBodyPart);
                        message.setContent(multipart);
                        Transport.send(message);
                   catch (SendFailedException ex)
                     ex.printStackTrace();
                   catch (MessagingException ex)
                     System.err.println("Exception. " + ex);
           catch (Exception e)
                System.out.println(e.toString());
    public static void main(String args[])
          Hashtable hash = new Hashtable();
          hash.put("host","213.312.230.211");
          hash.put("ccAddr","[email protected]");
         try
               Emailer objEmailer = new Emailer(hash);
              Boolean fromFlag = objEmailer.setFromAddr("[email protected]");
              String toAddresses = "[email protected]";
              String ccAddresses = "[email protected]";
              Boolean toFlag = objEmailer.setToAddr(toAddresses);
              Boolean ccFlag = objEmailer.setCCAddr(ccAddresses);
              Boolean subjectFlag  = objEmailer.setEmailSubject("Emailer.java");
              Boolean bodyFlag = objEmailer.setEmailBody("blah blah blahblha ");
              if((fromFlag.toString()).equals("true") && (toFlag.toString()).equals("true") && (bodyFlag.toString()).equals("true"))
                   objEmailer.sendEmail();
         catch(AddressException e)
              e.printStackTrace();
         catch(Exception e)
              e.printStackTrace();

    i.e example :
    u can do it in this way
    MimeBodyPart messageBody = new MimeBodyPart();
    messageBody.setText("your message body goes here");
    // attaching file i.e make separate object of body part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filePath);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(fileName);
    multipart.addBodyPart(messageBody);
    multipart.addBodyPart(messageBodyPart);
    mimemessage.setContent(multipart);
    Transport.send(mimemessage);

  • Problem in Mail deletion in POP3

    Hi
    I am using Pop3.
    I opened folder using
    folder.open (Folder.READ_WRITE);
    setting flag for deletion
    mimeMessages.setFlag (Flags.Flag.DELETED, true);
    then in finally block closing the folder
    if (mailbox.isConnected ()) {
    if(folder != null && folder.isOpen()) {
    try {
    folder.close (true);
    sometimes it is not deleting the messages.
    Please suggest something.
    Thanks
    Atal

    I am sorry but what do u mean by this? can u please explain in detail.
    actually most of times it works fine but in few cases mail deletion is failing.
    In my code: after folder.close (true); I just take a dump that comes successfully.
    The MailBox folder has been closed after deleting the ToBeDeleted Mails, if any, by folder.close method.
    MessageId of 1 th message which has been marked for Deletion : 1150475083.23686.prod-util-1.aspdeploy.com,S=57857
    MessageId of 2 th message which has been marked for Deletion : 1150475117.23813.prod-util-1.aspdeploy.com,S=6808
    MessageId of 3 th message which has been marked for Deletion : 1150475120.23818.prod-util-1.aspdeploy.com,S=9425
    MessageId of 4 th message which has been marked for Deletion : 1150475140.23852.prod-util-1.aspdeploy.com,S=6121
    these 4 messages were marked for deletion.
    then close called. after
    The MailBox folder has been closed after deleting the ToBeDeleted Mails, if any, by folder.close method.
    message, it again tries to retrieve the folder with messages
    Retrieving messages for mailbox ..
    MessageId of the: 1 th message is 1150475083.23686.prod-util-1.aspdeploy.com,S=57857
    MessageId of the: 2 th message is 1150475117.23813.prod-util-1.aspdeploy.com,S=6808
    MessageId of the: 3 th message is 1150475120.23818.prod-util-1.aspdeploy.com,S=9425
    MessageId of the: 4 th message is 1150475140.23852.prod-util-1.aspdeploy.com,S=6121
    MessageId of the: 5 th message is 1150475338.13255.prod-util-2.aspdeploy.com,S=7458
    MessageId of the: 6 th message is 1150475387.13339.prod-util-2.aspdeploy.com,S=6394
    MessageId of the: 7 th message is 1150475393.13357.prod-util-2.aspdeploy.com,S=59238
    MessageId of the: 8 th message is 1150475553.13615.prod-util-2.aspdeploy.com,S=86236
    first 4 messages are same which were not deleted.
    I have just attached the code. If you want to have a look then plz.
    thanks
    atal
    package com.deploy.email;
    import com.baltimore.jpkiplus.vaults.Vault;
    import com.baltimore.jpkiplus.x509.JCRYPTO_X509Certificate;
    import com.baltimore.jsmt.smime.JSMTException;
    import com.baltimore.jsmt.smime.SMIMEv2;
    import com.deploy.email.api.EmailException;
    import com.deploy.email.api.InitException;
    import com.deploy.email.api.ReceivedMessage;
    import com.deploy.email.config.LogicalMailboxConfiguration;
    import com.deploy.email.config.MailConfiguration;
    import com.deploy.email.config.PhysicalMailboxConfiguration;
    import com.deploy.email.util.SecureEmailHelper;
    import com.sun.mail.pop3.POP3Folder;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Vector;
    import javax.mail.Address;
    import javax.mail.AuthenticationFailedException;
    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.Store;
    import javax.mail.UIDFolder;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.naming.NamingException;
    import org.apache.log4j.Logger;
    * This class spawns a thread for each mailbox and pulls messages from those mailboxes at a specified interval.
    * Use start to initialize and stop to end the threads
    * Bug Fixes
    * - 8399 Broke out the mailServer into two separate potential servers; sendMailServer and receiveMailServer
    * This class was updated to reflect the receiveMailServer setting
    * 04/25/03 John Gemski
    * - 10619 Added support for the Lotus Notes Client as per the 3.x fix. Copied logic from 3.x as detailed
    * by Hari in the bug report
    * 08/13/03 John Gemski
    * - Added Email Client Calendaring support - John Gemski 10/21/2003
    * @see com.deploy.email.EmailChannel
    public class RetrieveMail implements Runnable {
    /** Used to tell the threads when to stop */
    private static boolean keepRunning=true;
    //anish For nationwide
    private int maximumsizeofinbox=-1;
    /** The messages on the mail server that have been pulled but not deleted */
    private HashMap messagesOnServer;
    /** These are the mailbox types. Will only be one here for the Azetra impl */
    private static List logicalMailboxes;
    /** The list of running threads. Need to be tracked so they can be interrupted upon stop */
    private static ArrayList receiveThreads;
    /** A reference to the EmailChannel object, which may contain updated information. */
    private static EmailChannel emailChannel = EmailChannel.getInstance();
    private static Logger log = Logger.getLogger(EmailChannel.LOGGER_MODULE_NAME);
    // Thread variables
    /** the configuration for the physical mailbox from which the emails are being pulled. */
    private PhysicalMailboxConfiguration tPhysicalMailbox;
    /** the logical type (OLJB, ScanWorld, Task Response, Resume) that the physical mailbox thread is pulling for */
    private String tLogicalType;
    /** JavaMail Store */
    private Store mailbox;
    // Acceptable Protocols to retrieve mail from the mail server.
    public static final int RECEIVE_MAIL_PROTOCOL_POP3 = 0;
    public static final int RECEIVE_MAIL_PROTOCOL_IMAP = 1;
    public static final int NUM_RECEIVE_MAIL_PROTOCOLS = 2;
    public static String [] RECEIVE_MAIL_PROTOCOL_NAME;
    /** Indicates whether or not the Secure Email feature is enabled. */
    private static boolean secureEmailEnabled =false;
    static {
    RECEIVE_MAIL_PROTOCOL_NAME = new String [NUM_RECEIVE_MAIL_PROTOCOLS];
    RECEIVE_MAIL_PROTOCOL_NAME [RECEIVE_MAIL_PROTOCOL_POP3] = "pop3";
    RECEIVE_MAIL_PROTOCOL_NAME [RECEIVE_MAIL_PROTOCOL_IMAP] = "imap";
    // FIX for socket hang issue (FIX PR 14253) while processing the mail
    public static final String SOCKET_READ_ERROR = "No inputstream from datasource";
    /** Constructor for new RetrieveMail thread.
    * @param phys_config the mailbox configuration for a specific physical mailbox (i.e. [email protected])
    * @param logical_type the logical type for this mailbox ("Resumes", "OLJB", "ScanWorld", or "TaskResponse")
    private RetrieveMail(PhysicalMailboxConfiguration phys_config, String logical_type) {
    this.tPhysicalMailbox = phys_config;
    this.tLogicalType = logical_type;
    * Retrieve email messages from a mail server for the particular physical mailbox indicated with the thread
    * @throws EmailException if any fatal error occurs with the retrieval or processing of the incoming emails
    private void retrieveMessages () throws EmailException {
    Vector msgVector = new Vector ();
    Vector deleteMsgVector = new Vector ();
    ReceivedMessage [] recMessages;
    MailConfiguration mailConfig = emailChannel.getMailConfiguration();
    long maxReceivedEmailSize = mailConfig.getMaximumReceiveSize();
    //Anish for Bug 20366 for Nationwide Patch 06
    maximumsizeofinbox = mailConfig.getMaximumsizeofinbox();
    // Synchronize on the mailbox object for the mailbox from which we
    // are going to retrieve messages. We don't want more than one
    // thread connected to a mailbox at a time, but we don't want to
    // prevent multiple different threads from being connected to
    // multiple different mailboxes simultaneously.
    synchronized (mailbox) {
    boolean throwingException = false;
    Folder folder = null;
    try {
    /* Fix for 8399 - use the getReceiveMailServer call instead of the
    * getMailServer call
    // Connect to the server for receiving mail.
    mailbox.connect (mailConfig.getReceiveMailServer(),
    tPhysicalMailbox.getMailboxName(),
    tPhysicalMailbox.getMailboxPassword());
    // We are only interested in the "INBOX" folder.
    folder = mailbox.getFolder ("INBOX");
    // Open with write permissions as well, so we can delete messages from the server
    folder.open (Folder.READ_WRITE);
    // Anish for Bug 20366 for Nationwide Patch 06
    //int numMessages = folder.getMessageCount ();
    int numMessages1 = folder.getMessageCount ();
    int numMessages = 0;
    //log.info("Anish123 " + maximumsizeofinbox);
    if (maximumsizeofinbox < 0)
    numMessages = numMessages1;
    else
              if (numMessages1 > maximumsizeofinbox) {
              numMessages = maximumsizeofinbox;
              //log.info("Anish try 1 " + numMessages1);
              else {
              numMessages = numMessages1;
              //log.info("Anish try 2 " + numMessages);
    //     log.info("Anish try 4 " + numMessages);
    // End by anish
    if (numMessages > 0) { // There are messages to retrieve
    Message [] messagesRaw = folder.getMessages ();
    // We need to cast the messages to MIME message objects so
    // that we can access some MIME message-specific functionality.
    MimeMessage [] mimeMessages = new MimeMessage [numMessages];
    for (int i = 0; i < numMessages; i++) {
    mimeMessages = (MimeMessage) messagesRaw [i];
    // We can only get messages totalling maxReceivedMessageSize bytes.
    // Calculate how many messages we may get and still stay under the limit.
    int numMessagesToRetrieve = 0;
    int i = 0;
    if( maxReceivedEmailSize > 0) {
    int totalSize = 0;
    numMessagesToRetrieve = 0;
    boolean reachedLimit = false;
    while ((i < numMessages) && !reachedLimit) {
    int messageSize = mimeMessages[i].getSize ();
    int newTotalSize = totalSize + messageSize;
    if (newTotalSize > maxReceivedEmailSize) {
    //if this is the first message then break out and process it
    if( i == 0 ) {
    i++;
    totalSize = newTotalSize;
    reachedLimit = true;
    else {
    totalSize = newTotalSize;
    i++;
    numMessagesToRetrieve = i;
    i = 0;
    else {
    numMessagesToRetrieve = mimeMessages.length;
    while( i < numMessagesToRetrieve )
    boolean gotMessage = false;
    String uniqueID = null;
    if( numMessagesToRetrieve > 0 ) {
    // Get the ID for the message
    uniqueID = getUniqueID (mimeMessages[i], folder);
    //By Anurag for Req#2907 to add Debugging Logs start
    log.info("MessageId of the: " + (i+1) + " th message is " + uniqueID);
    //By Anurag for Req#2907 to add Debugging Logs End
    // Check if we have previoiusly retrieved this message.
    Object value = messagesOnServer.get (uniqueID);
    gotMessage = (value != null);
    if (!gotMessage) { // Make sure message is filled in.
    boolean processMessage = true;
    try {
    if(secureEmailEnabled) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    mimeMessages[i].writeTo(os);
    InternetAddress[] senders = (InternetAddress[])mimeMessages[i].getFrom();
    InternetAddress[] recipients = (InternetAddress[])mimeMessages[i].getRecipients (Message.RecipientType.TO);
    Exception lastException = null;
    Vault v = null;
    for (int countRecipients = 0; countRecipients < recipients.length; countRecipients++) {
    lastException = null;
    v = null;
    // try to get the recipient's address from the Vault hash table
    log.info("Trying to get Vault for address: " + recipients[countRecipients].getAddress ());
    v = SecureEmailHelper.getVault (recipients[countRecipients].getAddress ());
    // we can't decrypt if we don't have a private key from the vault!
    if (v == null) {
    log.info("The PFX file for the email account: " + recipients[countRecipients].getAddress () + " is not found or invalid. Please correct.");
    lastException = new EmailException(EmailException.REASON_UNKNOWN, "The PFX file for the email account: " + recipients[countRecipients].getAddress () + " is not found or invalid. Please correct.");
    else {
    break;
    // if we came out with all exceptions, throw the last one we received.
    if (lastException != null) {
    log.error(lastException.getMessage(), lastException);
    throw lastException;
    SMIMEv2 smimer = new SMIMEv2(v);
    // Set up input and output streams to read an S/MIME message
    byte[] originalMessageBytes = os.toByteArray();
    String origMessStr = new String(originalMessageBytes);
    // The SMIMEv2 can't handle extra characters.
    // Noticed that messages contained an "+OK", which was causing problems
    // removed the entire line
    if(origMessStr.startsWith("+OK")) {
    int index = origMessStr.indexOf("\n");
    origMessStr = origMessStr.substring(index+1);
    byte[] revMessageStr = origMessStr.getBytes();
    ByteArrayInputStream input_source = new ByteArrayInputStream(revMessageStr);
    ByteArrayOutputStream output_sink = null;
    boolean smimeRecognized=true;
    boolean wasSigned=false;
    boolean wasEncrypted=false;
    // Making changes to reflect Baltimore's suggestion about layers
    ByteArrayInputStream newMessage = null;
    boolean done=false;
    // According to Baltimore, there can be two layers of encryption
    // inner and outer. It could be encrypted & signed, with it being either
    // encrypted on the outer layer and signed on the inner, or vice versa.
    // We want to ensure that this loop breaks out after either
    // 1. there were 2 layers sign/encrypted or encrypted/signed
    // 2. there was an error
    int layers=0;
    while(!done && layers < 2) {
    output_sink = new ByteArrayOutputStream();
    layers++;
         try {
    // This step must be don't before any cryptographic operations. It lets the SMIMEv2 class
    // figure out what it has as an input and where to place the output
    smimer.attachStreams(input_source, true, output_sink, false, false);
    catch (JSMTException jse) {
    // This is common since unencrypted and unsigned data cannot perform this function
    // Ideally, Baltimore says to use the type SMIMEv2.TYPE_DATA, but it never gets this
    // far since this fails.
    // We will skip the attempts to decrypt/verify the signature, since we know we won't
    // be able to interpret what type of message it is.
    smimeRecognized=false;
    // Will only be one layer
    done=true;
         log.debug("SMIME recognized: " + smimeRecognized);
    if(smimeRecognized) {
    // Get the S/MIME message type
    int nextdata = smimer.getMessageType();
    log.info("SMIME message type: " + nextdata);
    if (nextdata == smimer.TYPE_SIGNED) { // Signed message
    wasSigned=true;
    boolean matchedSender = false;
    // Didn't know you could have multiple "from" in an email address
    // Right now, only one of the "froms" has to have a certificate
    for(int s=0; s < senders.length; s++) {
    // get the sender's address
    String from_sender = senders[s].getAddress();
    try {
    // retrieve the certificates from the LDAP
    JCRYPTO_X509Certificate[] senderCerts = null;
    senderCerts = SecureEmailHelper.getCertificatesFromLDAP(from_sender);
    if(senderCerts!=null) {
    // verify() needs to take in a chain of certificates
    com.baltimore.jsmt.pkcs7.CertificateChain cc= new com.baltimore.jsmt.pkcs7.CertificateChain();
    // create certificate chain
    for(int k=0; k < senderCerts.length; k++) {
    cc.addCertificate(senderCerts[k]);
    // verify the Certificate Chain against the message's certs
    if(smimer.verify(cc)) {
    // found a match, the message was verified
    matchedSender=true;
    break;
    else
    log.error("Could not verify the sender" + from_sender);
    done=true;
    catch(NamingException ne) {
    log.error("There was a problem connecting to the LDAP for " + from_sender,ne);
    done=true;
    // if none of the senders matched, we need to not process
    // the email message, since it will be unreadable
    if(!matchedSender) {
    StringBuffer sendString = new StringBuffer();
    for(int s=0; s < senders.length; s++) {
    String from_sender = senders[s].getAddress();
    sendString.append(" : " );
    sendString.append(from_sender);
    processMessage = false;
    log.error("Could not find certificate for any of the senders" + sendString.toString());
    done=true;
    else if (nextdata == smimer.TYPE_ENVELOPED) { // Encrypted message
    log.debug("SMIME Encrypted message!");
    wasEncrypted = true;
    try {
    log.debug("SMIME Decrypting message...");
    // Decrypts the message
    smimer.openEnvelope();
    catch (JSMTException jse) {
    // Could not decrypt message
    log.error("Could not decrypt message: " + jse.getMessage (), jse);
    processMessage = false;
    done=true;
    else {
    log.debug("Unrecognized type");
    // doesn't seem to get here since Baltimore toolkit doesn't accept
    // nonencrypted, nonsigned emails (it should though). Keep here for future
    // releases of the toolkit
    done = true;
    // Now that we have output_sink,
    // retrieve the bytes
    byte[] processedBytes = output_sink.toByteArray();
    newMessage = new ByteArrayInputStream(processedBytes);
    input_source = new ByteArrayInputStream(processedBytes);
    else {
    // only for the first time around, revert to original
    if(layers==1) {
    // Keep original message
    newMessage = new ByteArrayInputStream(revMessageStr);
    log.debug("wasSigned: " + wasSigned + " wasEncrypted: " + wasEncrypted);
    // create the mime message again
    mimeMessages[i] = new MimeMessage(emailChannel.getSession(),newMessage);
    mimeMessages[i].setFrom (senders[0]);
    mimeMessages[i].setRecipients (Message.RecipientType.TO, recipients);
    // decrypted/verified data is automatically written to output_sink
    input_source.close();
    output_sink.close();
    // If the message wasn't signed, we can still process the message
    // if the settings allow the server to process unsigned messages
    // If not, set the flag to not process this message
    if(!tPhysicalMailbox.getAcceptUnsignedEmail() && !wasSigned) {
         log.info("Server configuration does not allow unsigned emails.");
    processMessage = false;
    // If the message wasn't encrytped, we can still process the message
    // if the settings allow the server to process unencrypted messages
    // If not, set the flag to not process this message
    if(!tPhysicalMailbox.getAcceptUnencryptedEmail() && !wasEncrypted) {
    log.info("Server configuration does not allow unencrypted emails.");
    processMessage = false;
    if(processMessage) {
    MimeMessage m = mimeMessages[i];
    if( maxReceivedEmailSize > 0 && m.getSize() > maxReceivedEmailSize ) {
    try {
    m = constructDummyMsg( m, m.getSize() );
    catch (Exception e) {
    // Add message to a list of messages to be deleted after
    // finished retrieving messages.
    deleteMsgVector.addElement (uniqueID);
    ReceivedMessage receivedMessage =
    new ReceivedMessage (m, uniqueID);
    msgVector.addElement (receivedMessage);
    else {
    log.info("Email could not be processed.");
    deleteMsgVector.addElement (uniqueID);
    catch (EmailException ee) {
    log.error("Email Exception", ee);
    deleteMsgVector.addElement (uniqueID);
    } // mail socket hang fix
    catch (javax.mail.MessagingException e) {
    String message = e.getMessage();
    // if it's a socket hang issue due to network outage, we want to logout and refetch the messages.
    if (message.equals(SOCKET_READ_ERROR)) {
    log.error("Socket timed out. Closing the connection", e);
    messagesOnServer.clear();
    throw new EmailException(

  • A problem with reveive mail

    I have retrieve a message from the server,and then i used save the content(is a Multipart)
    in to a byte[] and save it into a database;my problem is how can i use the byte[] to form
    a Multipart?for now i want to use it to fetch the bodyparts in it.i have use this to form :
    byte[]attachment=reasultSet.getBytes("attachment");
    byteArrayDataSource ds=new byteArrayDataSource(attachment);
    mpart=new MimeMultipart(ds);
    but while i use the method of this Multipart,i got an javax.mail.internet.ParseException,
    i am very appreciate if anyone can tell me how to solve this problem

    Hi. weixiazero.
    I'm illmare..
    I'll show you a simple code to solve your problem.
    It's, first of all, simply get an object from MimeMessage with using getContent method. And then add all object contents to array list..
    you can be adjusted this code to multipart messages not to text/plain type.
    If you know datail method for java mail system, toss me a e-mail.
    My E-mail add is [email protected]..
    I wish it will help you to solve your's
    Illmare wrote.
    blob..blob..
    oMsg = mMsg.getContent();
    rBody.addAll(getMsgBodyPart(oMsg));
    blob
    String getMsgBody(ArrayList rBody) throws MessagingException,IOException
    BufferedReader cBodyPartIn=null;
    MimeBodyPart cMimeBodyPart=null;
    String sBodyContentType=""; //MimeBodyPart content-type
    String sHtmlBody="";
    String sTextBody="";
    boolean bIsBody;
    int nCnt = rBody.size();
    for (int i=0;i<nCnt;i++)
    cMimeBodyPart=(MimeBodyPart) rBody.get(i);
    sBodyContentType=cMimeBodyPart.getContentType();
    bIsBody=isBody(sBodyContentType);
    if (bIsBody==true)
    cBodyPartIn = new BufferedReader(new InputStreamReader cMimeBodyPart.getInputStream()));
    int x=-1;
    if (sBodyContentType.toLowerCase().indexOf("html")>=0)
    while ((x=cBodyPartIn.read())!=-1) {
    sHtmlBody+=(new Character ((char) x)).toString();
    break; //exit For-Loop
    else
    while ((x=cBodyPartIn.read())!=-1) {
         sTextBody+=(new Character ((char) x)).toString();
    }//For close
    if (sHtmlBody !=""){ return sHtmlBody;}
    else if(sTextBody != "") { return sTextBody;}
    else { return "No Contents";}
    }

Maybe you are looking for