JavaMail

I have written a program which sends a simple e-mail conformation, it compiles with no errors and runs no problem, well it looks like it does, the only problam is , no email comes through.
i have attached the source code, would anyone be able to help?
thanks in advance
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class email{
     private static void send(String host, String from, String to, String subject, String time){
          //setup the contents of the e-mail message
          String contents = ("Email content");
          //set the properties
          Properties prop = System.getProperties();
          //set up the mail server
          prop.put("mail.smtp.host", host);
          //create a new session
          Session session = Session.getDefaultInstance(prop, null);
         try {
          //define the message
          MimeMessage message = new MimeMessage(session);
          //set who the message is from
          message.setFrom(new InternetAddress("[email protected]"));
          //set who the message is to
          message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
          //set the message subject
          message.setSubject("Details of Meeting " + subject);
          //set the message content
          message.setContent(contents + footer, "text/plain");
          //send the message
          Transport.send(message);
         //exception handling
         } catch (MessagingException mex) {
         System.out.println("\n--Exception handling in sending email");
         mex.printStackTrace();
         System.out.println();
         Exception ex = mex;
         do {
          if (ex instanceof SendFailedException) {
              SendFailedException sfex = (SendFailedException)ex;
              Address[] invalid = sfex.getInvalidAddresses();
              if (invalid != null) {
               System.out.println("    ** Invalid Address");
               if (invalid != null) {
                   for (int i = 0; i < invalid.length; i++)
                    System.out.println("         " + invalid);
          Address[] validUnsent = sfex.getValidUnsentAddresses();
          if (validUnsent != null) {
               System.out.println(" ** ValidUnsent Address");
               if (validUnsent != null) {
               for (int i = 0; i < validUnsent.length; i++)
                    System.out.println(" "+validUnsent[i]);
          Address[] validSent = sfex.getValidSentAddresses();
          if (validSent != null) {
               System.out.println(" ** ValidSent Address");
               if (validSent != null) {
               for (int i = 0; i < validSent.length; i++)
                    System.out.println(" "+validSent[i]);
          System.out.println();
          if (ex instanceof MessagingException)
          ex = ((MessagingException)ex).getNextException();
          else
          ex = null;
     } while (ex != null);
     }//end of catch
}//end of send email
     public static void main(String [] args){
          send("iserve1.infj.ulst.ac.uk", "[email protected]", "[email protected]", "Conformation", "Whenever");}

It doesn't work because of the 'relay request'. Most smtp servers will reject a request for relay because of the problems of spamming and somewhat ironically, many email spoofers will hack into university servers as they have a less stringent security management than commercial ISP/servers ... hmmm.
I assume that you have set up an email server at the college, contact the administrator there and ask him/her to register your password and user name with the smtp server.
- Also you may need a 'Helo' message before you send the request.
- You can also check the javamail forum here at this site.
Hope that helps.

Similar Messages

  • Web Application and Custom JavaMail Providers

    We have a web application that uses custom JavaMail Providers on Weblogic 7.0.
    The structure of the WAR file is as follows:
    |-WEB-INF
    |-lib
    |-activation.jar
    |-mail.jar (as provided by Sun for JavaMail 1.2)
    |-custommail.jar (custom JavaMail providers)
    |-... (other jars for web application).
    Now the JavaMail Session object cannot find the custom providers as it appears the Web Container is loading the JavaMail classes (Session) from the WebLogic.jar instead of mail.jar from the web application's lib directory.
    How can I configure the web application to load classes from the mail.jar in the applications lib directory?.
    This configuration works on Tomcat 4.0.4.
    Vikash

    This is standard behavior in WebLogic - the child classloader (the
    classloader for the web applicaiton) will always
    delegate to the parent classloader (the system classloader), and so it will
    alwyas find the ones included in weblogic.jar
    first.
    You can get around this in two ways:
    a) Put the classes in weblogic's classpath (Before weblogic.jar)
    b) You can set the "Prefer Web-Inf Classes" attribute of a web application
    (see Admin console).
    In this case the web application classloader will not delegate, but
    always look locally first.
    Just be careful in this scenario not to pass an object created by the
    web applicatino classloader to say
    an EJB. ie. don't pass a mail session object, as then you'll get a
    classcastexception.
    Regards,
    Jon

  • 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

  • Problem with relaying in JavaMail

    Hi all,
    I am having what seems to be a common problem with people attempting to send emails using JavaMail. I always get the following error....
    class javax.mail.SendFailedException: 550 relaying mail to compuserve.com is not allowed.
    I have done some research and I understand that most ISP's will not allow relaying through their servers for spamming reasons. Some people seem to have asked this question before but never been able to get an answer. What can be done to overcome this problem??? I need to send automated emails to people buying stuff from our website. I want to do this by reading the info from a database and sending them a personalised email based on the info in the database.
    Please help,
    Bow_wow.

    You are running all your mail through Exchange on the server? Whose server is this, yours? If it is yours, then you should be able to configure it to accept relaying from the machine where you are trying to send the e-mails from. If it is somebody else's, then talk to them about accepting relaying from your IP address.

  • Problem with Javamail in Red Hat

    Good afternoon.
    I have a problem with javamail in Red Hat.
    When i send a email in windows with my application, works well. But in Red Hat no works.
    Gives the following error:
    Java.lang.ClassCastException .... gnu.mail.handler.TextPlain
    Does anyone know that happens?

    You have much to learn. This is the wrong forum for most of it.
    You should be able to use the package manager in Linux to
    uninstall the Gnu version. Then read this:
    [http://java.sun.com/products/javamail/FAQ.html#install|http://java.sun.com/products/javamail/FAQ.html#install]

  • Sending an Email using JavaMail from the Net Work of my company not workin

    Hi,
    If any body would reply to this issue as soon as possible..
    I have developed a simple java mail program which sends an email to gmail (smtp.gmail.com) and works fine at home , So when i sent the same
    from my office(at company) it did not work and exception was reported saying ...... could not connect to host .smtp.gmail.com... port .. .
    I think it's a network problem.
    So If any body has a suggestion ?
    If so can any body give a simple code for this issue.
    Regards,

    No, I don't mean the msgshow.java demo program. I mean the [JavaMail FAQ|http://java.sun.com/products/javamail/FAQ.html].
    In particular, the section about debugging connection problems and the section
    about connecting to Gmail.
    Find it yet?

  • How to download a .pdf file from a JavaMail application?

    hi to all,
    iam unable to download a .pdf file from a mailserver using
    my javamail application.i have downloaded all kind of files except .pdf.
    my code snipnet:
    public static void dumpPart(Part p) throws Exception {
    //     if (p instanceof Message)          dumpEnvelope((Message)p);
              System.out.println("CONTENT-TYPE: " + p.getContentType());
              Object o = p.getContent();
              if (o instanceof String) {
                   System.out.println("This is a String");
                   System.out.println((String)o);
                   } else if (o instanceof Multipart) {
                        System.out.println("This is a Multipart");
                        Multipart mp = (Multipart)o;
                        int count = mp.getCount();
    System.out.println("****************************************");
    System.out.println("count" + count);
    System.out.println("****************************************");
                        for (int i = 0; i < count; i++){
                             System.out.println("CONTENT-TYPE: " + p.getContentType());
                             dumpPart(mp.getBodyPart(i));
                        } else if (o instanceof InputStream) {
                             System.out.println("This is just an input stream");
                             InputStream is = (InputStream)o;
                             String filename=System.currentTimeMillis()+".exe     ";
                             FileOutputStream fos=new FileOutputStream(filename);
                             int c;
                             while ((c = is.read()) != -1)
                                  //System.out.write(c);
                                  fos.write((char)c);
    }//dumpPart
    what's wrong with this code?
    Nagaraju.G

    fos.write((char)c);Converting the byte to a char is unnecessary and probably harmful. Just do this: fos.write(c);

  • JavaMail application hanged with no error throwed at Transport.send

    JavaMail application hanged with no error throwed at Transport.send,even though I set the timeout property
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    import javax.mail.internet.MimeUtility;
    public class tt {
         static Properties props=null;
         static boolean needAuth=true;
         static MailAuthenticator authenticator = null;
         static String host="host";
         static String account="account";
         static String password="pwd";
         static String sender="sender";
          * @param args
          * @throws Exception
         public static void main(String[] args) throws Exception{
               if (props == null) {
                     props = new Properties();
                     props.put("mail.smtp.host", host);
                     props.put("mail.smtp.timeout      ", "1000");
                     props.put("mail.smtp.connectiontimeout      ", "1000");
    //                 props.put("mail.debug", "true");
                     props.put("mail.smtp.auth", String.valueOf(needAuth));
                     authenticator = new MailAuthenticator(account, password);
                 MailData mailData = new MailData();
                 mailData.setSubject("altireport mail configuration");
                 mailData.setContent("mail server has been configured successfully.");
                 mailData.setRecipients(new String[]{"[email protected]"});
                 final Session session = Session.getInstance(props, authenticator);
                 final MimeMessage msg = new MimeMessage(session);
                 InternetAddress from = new InternetAddress(sender);
                 msg.setFrom(from);
                 //        msg.setSender(from);
                final InternetAddress[] addressTo = new InternetAddress[mailData.getRecipients().length];
                 for (int i = 0; i < mailData.getRecipients().length; i++) {
                     addressTo[i] = new InternetAddress(mailData.getRecipients());
         msg.addRecipients(Message.RecipientType.TO, addressTo);
         //msg.setSubject(mailData.getSubject());
         msg.setSubject(MimeUtility.encodeText(mailData.getSubject(), "UTF-8", "B"));
         MimeBodyPart bodyPart1 = new MimeBodyPart();
         bodyPart1.setContent(mailData.getContent(), "text/plain; charset=UTF-8");
         MimeMultipart multipart = new MimeMultipart();
         multipart.addBodyPart(bodyPart1);
         msg.setContent(multipart);
         msg.setSentDate(new Date());
    //     msg.saveChanges();
         for(int i=0;i<10;i++){
              new Thread(new Runnable(){
                             public void run() {
                             try {
                                  System.out.println("send...");                                   
                                  Transport.send(msg);
                                  } catch (Exception e) {
                                       e.printStackTrace(System.out);
                        System.out.println("end!");
              }).start();
    class MailData {
    private String[] recipients = null;
    private String subject = null;
    private String content = null;
    private String attachment = null;
    private String attachmentName = null;
    * @return the attachment
    public String getAttachment() {
    return attachment;
    * @param attachment the attachment to set
    public void setAttachment(String attachment) {
    this.attachment = attachment;
    * @return the content
    public String getContent() {
    return content;
    * @param content the content to set
    public void setContent(String content) {
    this.content = content;
    * @return the recipients
    public String[] getRecipients() {
    return recipients;
    * @param recipients the recipients to set
    public void setRecipients(String[] recipients) {
    this.recipients = recipients;
    * @return the subject
    public String getSubject() {
    return subject;
    * @param subject the subject to set
    public void setSubject(String subject) {
    this.subject = subject;
    * @return the attachmentName
    public String getAttachmentName()
    return attachmentName;
    * @param attachmentName the attachmentName to set
    public void setAttachmentName(String attachmentName)
    this.attachmentName = attachmentName;
    class MailAuthenticator extends Authenticator {
    private PasswordAuthentication authentication;
    public MailAuthenticator(String account, String password) {
    authentication = new PasswordAuthentication(account, password);
    protected PasswordAuthentication getPasswordAuthentication() {
    return authentication;
    I have tried use session to get a SMTPTransport instance to use sendMessage ,but still have the same problem.No exception ,No error.
    This problem doesn't appear always. It appears sometimes.
    I hope get help for someone who has the solution for this problem.
    Thanks in advanced.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Ok, I think I see the problem:
         props.put("mail.smtp.timeout      ", "1000");
         props.put("mail.smtp.connectiontimeout      ", "1000");
    Why do you have spaces at the end of the property names?
    Those spaces are not being ignored, which means you've
    set the wrong properties.

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

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

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

  • How to create a group mailing list in JavaMail?

    Hello,
    I've been searching through the entire API, specifically the InternetAddress class and I can't seem to find out how to create a group/mailing list. Does anyone know how to do this?
    That is, I would like to be able to group a bunch of e-mail addresses together and give that group a name "my friends". Then send it off using this 'group mail address' as opposed to an array of InternetAddress[]. Then when the recipients receive the e-mail, they see "my friends" in the To: field, instead of everyone's e-mail address...
    Is this possible in JavaMail? I've tried many things like creating an InternetAddress object passing in a comma-delimited list of e-mail addresses but it doesn't like it.
    Thanks in advance!

    Hi:
    I have the same problem. I've read JavaMail implements RFC 822 which allow mailing lists. But, �how can I implement it with JavaMail?
    Best regards,
    Fabio Galarraga.

  • How can i add a new user and change user'password with javamail?

    how can i add a new user and change user'password from a mailserver with javamail?
    email:[email protected]

    Well user creation and updation is a system property..U need to go through that part...as it depends on the system you are hosting pout your application...
    if it is linux...u have to use some shell programming\
    bye for now let me know if this guides you or if you need some more stuff.
    bye

  • Some PDF attachments are corrupted when emailed using javamail

    I have a java class that takes a file name, 'To' email, and 'From' email as parameters, and then emails the named file to the specified address as a Multipart email.
    The problem that I am facing is that sometimes the PDF cannot be opened when it arrives because it is corrupt. I know that prior to sending, the PDF opens without issue, so the problem is in the code somewhere.
    There are a couple of oddities here:
    1) PDFs that get corrupted and PDFs that do not get corrupted are generated from the same source (Oracle Report), so I believe that rules out a problem with malformed emails?
    2) If I compare the PDF before it gets sent to the PDF that arrives in my inbox using a hex editor (XVI32), the files are identical except that an extra character is getting added to the corrupt PDFs at the end of each line - hex '0A', which corresponds to ASCII linefeed. This indicates to me that maybe there is a problem with the way that the file is getting encoded when it is read. If I remove all of the 0A characters, the file opens correctly.
    I believe that the code I am using is set up correctly, as I have looked at countless examples of this online to try to find my problem. Hopefully someone can point me in the right direction. Code is included below.
    Thanks,
    Nick
    import java.util.*;
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.*;
    import javax.mail.internet.*;
    public class test {
        public static void main(String args[]) {
            System.out.println("entered TEST email class");
            if (args.length < 3) {
                System.out.println("Invalid number of arguments. Syntax is 'java test <fileName> <fromEmail> <toEmail>'");
            } else {
                System.out.println("Correct number of arguments.");
                send(args[0], args[1], args[2]);
        public static void send(String fileName, String fromEmail, String toEmail) {
            System.out.println("Made it to SEND method");
            try {
                Properties props = new Properties();
                props.put("mail.smtp.host", "email.host");
                Session session = Session.getDefaultInstance(props, null);
                MimeMessage msg = new MimeMessage(session);
                //set from/to email addresses
                System.out.println("Setting email addresses...");
                msg.setFrom(new InternetAddress(fromEmail));
                msg.setRecipients(javax.mail.Message.RecipientType.TO, toEmail);
                //set email subject
                System.out.println("Setting subject...");
                msg.setSubject("email from TEST class");
                //define a body part for the email text and add text to it
                System.out.println("Setting body...");
                MimeBodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent("This is the email body. Here is some more body.", "text/html");
                //add code for attachment here!!
                System.out.println("Setting attachment...");
                MimeBodyPart attachFilePart = new MimeBodyPart();
                FileDataSource fds =
                        new FileDataSource(fileName);
                attachFilePart.setDataHandler(new DataHandler(fds));
                attachFilePart.setFileName(fds.getName());
                //define a multipart, and add the text body part and the attachment body part to it
                System.out.println("Building message...");
                Multipart mp = new MimeMultipart();
                mp.addBodyPart(messageBodyPart);
                mp.addBodyPart(attachFilePart);
                //add the multipart to the message
                msg.setContent(mp);
                //send the email
                System.out.println("Sending message...");
                Transport.send(msg);
                System.out.println("Email has been sent!");
            } catch (Exception e) {
                System.out.println("Error in test.send method: " + e.getMessage());
    }Edited by: nbacon on Sep 2, 2010 12:12 PM

    Normally pdf files are text, with any binary data represented as encoded text. If your pdf files
    include raw binary data, JavaMail can be confused. JavaMail will try to guess what encoding
    is appropriate for your data. If the data is mostly text, JavaMail will use quoted-printable encoding,
    and will canonicalize the text lines to end with CRLF (0x0D, 0x0A). A 0x0D in the binary will look
    like an end of line and will turn into 0x0D, 0x0A.
    You can force JavaMail to use base64 encoding for your data, which will preserve the binary
    data exactly, by using
    attachFilePart.setHeader("Content-Transfer-Encoding", "base64");
    after setting the content for the part.
    Alternatively, you could figure out how to generate pdf files that don't include raw binary data.

  • Is there any problem to use multiple threads to send email with JavaMail

    Dear all,
    I am using JavaMail 1.3.2 to send emails with SMTP, it works very well for a long time.
    But one day, I found that the email service hanged and I could never send email again until I restart the tomcat. I found that the reason was a deadlock had been created, the required resource for sending email had not been released.
    I guess the error is due to multiple threads are sending email at the same time. I made a test to create seperate thread for sending each email. After few days, I found this deadlock happened again. So, my question is: Can I use JavaMail with multiple threads? If not, I may need to sychronized all the thread that using JavaMail. I would like to make sure this is the reason for causing the deadlock problem.
    Here is part of my code for using JavaMail:
    transport = session.getTransport("smtp");
    transport.connect(email_host, smtp_user, smtp_pass);
    message.saveChanges();
    transport.sendMessage(message,message.getAllRecipients());
    which is very standard call, and it worked well for a long time.
    Here is part for my thread dump on tomcat:
    (Thread-339)
    - waiting to lock <0x5447c180> (a sun.nio.cs.StandardCharsets)
    (Thread-342)
    - locked <0x5447c180> (a sun.nio.cs.StandardCharsets)
    It seems that these happened after call the method transport.sendMessage() or message.updateChanges()
    , and the underlying implementation may require the JRE StandardCharsets object. But the object had been locked and never be released. So, the sendMessage() or updateChanges() can't be completed.
    Please give me some helps if you have any idea about it.
    Thanks very much!
    Sirius

    Note that the Nightly build gets updated daily (and sometimes more than once in case of a respin) and it is always possible that something goes wrong and it doesn't work properly, so be prepared for issues if you decide to stay with the Nightly build and make sure to have the current release with its own profile installed as well in case of problems.
    See also:
    * http://kb.mozillazine.org/Testing_pre-release_versions
    *http://kb.mozillazine.org/Creating_a_new_Firefox_profile_on_Windows
    *http://kb.mozillazine.org/Shortcut_to_a_specific_profile
    *http://kb.mozillazine.org/Using_multiple_profiles_-_Firefox

  • Javamail to send message with a custom messageclass to outook exchange

    Hello,
    I developed a microsoft outlook addin which added a custom message class to our outlook exchange. Now if a user sends a message of type "IPM.Note.OurCustomForm"; the recipient gets our custom addin when the message is received. My question is, is there any way to use JavaMail to send a message from our server, which is all in Java, which the Microsoft Office exchange will pick up as the "IPM.Note.OurCustomForm"; message class and display my addin.
    Some example code, or reference to similar problems would be appreciated, I have not programmed in Java since I graduated many a years ago :). Also, I was hoping to do this without using third party software (unless it is free), but I would none the less appreciate information about them too.
    Thanks much,

    I know nothing about Exchange, so all I can give you is a general approach to
    solving this problem. Remember that Exchange is full of Microsoft proprietary
    features that are not defined by any standard or specification.
    You need to learn how to construct a MIME format message that is equivalent
    to the new Exchange-proprietary message you created. One way to do that would
    be to use JavaMail (or some other non-Outlook email client) to read a message of
    that type from Exchange and examine the MIME structure of that message. That
    should give you enough information to construct a MIME message using JavaMail
    that has the same structure (MIME types, headers, etc.).
    The second part is constructing the actual content of the message. Since you
    created the new custom message class, maybe you already know how to do that.
    But if you used a tool to do that you might not understand the raw format of that
    message, in which case you may need to reverse engineer the format by reading
    sample MIME messages in that format.
    Does that help?

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

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

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

Maybe you are looking for

  • No DVD templates in Premiere Elements 2

    I have been using PE2 with good results for a couple of years now on my old PC but recently upgraded my hardware and transferred PE2 onto my new machine (still running XP Pro as did my old PC). In my latest project, the first on this machine, I came

  • I have reinstalled iTunes on my Windows pc. Several times.

    When I open iTunes, I receive the message "The registry settings used by the iTunes drivers for importing and burning CDs and DVDs are missing.This can happen as a result of installing other CD burning software. Please reinstall iTunes." I have tried

  • EA3: SQL Developer freezes on index creation

    OS Name     Microsoft Windows XP Professional Version     5.1.2600 Service Pack 2 Build 2600 Oracle SQL Developer 1.5.053.04 Java Platform: 1.5.0_07 Oracle server version: 10.2.0.2.0 Oracle Server O/S: RedHat Linux 64 bit Problem replication: Open a

  • Invalid objects found in Repository

    I am installing grid control 11.1 to redhat 5.2, with repository database of 11.2 locate on the same host. At step 7 of 13 connect to database, I provided the host, port, service and sys password and clicked Next, and I got a simple error messageInva

  • Can't uninstall or install a program on my laptop

    Can't uninstall or install a program on my laptop: User account control popup and the yes option is deactivated