?
Solved

Sending e-mails with java

Posted on 2003-03-31
13
Medium Priority
?
543 Views
Last Modified: 2013-11-24
How can I send e-mails with Java???
I downloaded and installed all Java mail libraries. I also followed the docs and created a small program that was supposed to send e-mails, but I am using Microsoft Server Exchange, and the libraries use SMTP servers. How can I use the Java mail libraries to send e-mails through Microsoft Exchnage?????

Thanks for your time
0
Comment
Question by:dyma82
  • 5
  • 4
  • 2
  • +2
13 Comments
 
LVL 7

Expert Comment

by:rugdog
ID: 8241506
MS Exchage knows SMTP, it should work, unless the service is disabled by the administrator. try this to check if SMTP is indeed up:
  telnet exchange-server-name-or-ip 25

it should respond with something like:

220 exchange-server-name-or-ip ESMTP Server (Microsoft Exchange Internet Mail Service 5.5.2656.59) ready
0
 
LVL 7

Expert Comment

by:enzogoy
ID: 8243210
wondering that you are talking about Java or JavaScript.  Does Java do the mail things tooooo????
0
 

Expert Comment

by:desmondliu
ID: 8243545
Microsoft exchange server is mail server, right? of course you can send e-mail using JavaMail.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Expert Comment

by:Venci75
ID: 8243670
import javax.mail.*;
import javax.mail.internet.*;
...
Properties props = new Properties();
props.put("mail.smtp.host","mail");
Session session = Session.getDefaultInstance(props,null);
Message message = new MimeMessage(session);
// init the message
session.getTransport().send(message);
0
 
LVL 1

Author Comment

by:dyma82
ID: 8246423
This is my class:

public class EPoliceMail
{
     public static void sendMail(String to, String subject, String body)
     {
          try
         {
           Properties props = new java.util.Properties();
     
           // -- Attaching to default Session, or we could start a new one --
     
           props.put("mail.smtp.host", "bilko.mySMTPServer.com");
           Session session = Session.getDefaultInstance(props, null);
     
           // -- Create a new message --
           Message msg = new MimeMessage(session);
     
           // -- Set the FROM and TO fields --
           msg.setFrom(new InternetAddress("test"));
           msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to, false));
     
           // -- We could include CC recipients too --
           // if (cc != null)
           // msg.setRecipients(Message.RecipientType.CC
           // ,InternetAddress.parse(cc, false));
     
           // -- Set the subject and body text --
           msg.setSubject(subject);
           msg.setText(body);
     
           // -- Set some other header information --
           msg.setHeader("X-Mailer", "LOTONtechEmail");
           //msg.setSentDate(new Date());
     
           // -- Send the message --
           Transport.send(msg);
     
           System.out.println("Message sent OK.");
         }
         catch (Exception ex)
         {
                ex.printStackTrace();
         }
     }
}

Still it does not work. I know for sure our e-mail server is working because I was able to telnet into it and it was working.
However, it keeps throwing this exception :

javax.mail.NoSuchProviderException: smtp
     at javax.mail.Session.getService(Session.java:611)
     at javax.mail.Session.getTransport(Session.java:541)
     at javax.mail.Session.getTransport(Session.java:484)
     at javax.mail.Session.getTransport(Session.java:464)
     at javax.mail.Session.getTransport(Session.java:519)
     at javax.mail.Transport.send0(Transport.java:155)
     at javax.mail.Transport.send(Transport.java:81)
     at com.mdpd.epolice.server.mobilemessaging.EPoliceMail.sendMail(EPoliceMail.java:48)
     at com.mdpd.epolice.server.mobilemessaging.CadDataLoader.main(CadDataLoader.java:72)


Any help please !!!!!!!!
0
 

Accepted Solution

by:
desmondliu earned 200 total points
ID: 8250271
To send mail through MS Exchange server, you will need authentication with correct user name and password. Please refer to the following code piece.

/*
Some SMTP servers require a username and password authentication before you
can use their Server for Sending mail. This is most common with couple
of ISP's who provide SMTP Address to Send Mail.

This Program gives any example on how to do SMTP Authentication
(User and Password verification)

This is a free source code and is provided as it is without any warranties and
it can be used in any your code for free.

Author : Sudhir Ancha
*/

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;

/*
  To use this program, change values for the following three constants,

    SMTP_HOST_NAME -- Has your SMTP Host Name
    SMTP_AUTH_USER -- Has your SMTP Authentication UserName
    SMTP_AUTH_PWD  -- Has your SMTP Authentication Password

  Next change values for fields

  emailMsgTxt  -- Message Text for the Email
  emailSubjectTxt  -- Subject for email
  emailFromAddress -- Email Address whose name will appears as "from" address

  Next change value for "emailList".
  This String array has List of all Email Addresses to Email Email needs to be sent to.


  Next to run the program, execute it as follows,

  SendMailUsingAuthentication authProg = new SendMailUsingAuthentication();

*/

public class SendMailUsingAuthentication
{

  private static final String SMTP_HOST_NAME = "myserver.smtphost.com";
  private static final String SMTP_AUTH_USER = "myusername";
  private static final String SMTP_AUTH_PWD  = "mypwd";

  private static final String emailMsgTxt      = "Online Order Confirmation Message. Also include the Tracking Number.";
  private static final String emailSubjectTxt  = "Order Confirmation Subject";
  private static final String emailFromAddress = "sudhir@javacommerce.com";

  // Add List of Email address to who email needs to be sent to
  private static final String[] emailList = {"mark@yahoo.com", "robin@javacommerce.com"};

  public static void main(String args[]) throws Exception
  {
    SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
    smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
    System.out.println("Sucessfully Sent mail to All Users");
  }

  public void postMail( String recipients[ ], String subject,
                            String message , String from) throws MessagingException
  {
    boolean debug = false;

     //Set the host smtp address
     Properties props = new Properties();
     props.put("mail.smtp.host", SMTP_HOST_NAME);
     props.put("mail.smtp.auth", "true");

    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++)
    {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);


    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
 }


/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
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);
    }
}

}
0
 
LVL 9

Expert Comment

by:Venci75
ID: 8251934
are you sure that your mail.jar is ok?
0
 
LVL 1

Author Comment

by:dyma82
ID: 8254219
desmondliu :

I tried your code and it does not compile. Line
"Authenticator auth = new SMTPAuthenticator();" has the following error : Type mismatch: cannot convert from javax.mail.PasswordAuthentication to javax.mail.Authenticator     EPoliceMail.java    

I check the mail docs and I could find any way to create a new  Authenticator since it is an abstract class.

Any help with this??????
Thanks a lot.
0
 
LVL 1

Author Comment

by:dyma82
ID: 8254507
Never mind about my last comment. Your code compiled and ran, but I still do get this exception:

javax.mail.NoSuchProviderException: smtp
     at javax.mail.Session.getService(Session.java:611)
     at javax.mail.Session.getTransport(Session.java:541)
     at javax.mail.Session.getTransport(Session.java:484)
     at javax.mail.Session.getTransport(Session.java:464)
     at javax.mail.Session.getTransport(Session.java:519)
     at javax.mail.Transport.send0(Transport.java:155)
     at javax.mail.Transport.send(Transport.java:81)
     at com.ddpd.server.messaging.ddpdMail.sendMail(ddpdMail.java:58)
     at com.ddpd.server.messaging.Tester.main(Tester.java:16)

I also tested my email server and I think it works. I did telnet to it on port 25 and it responded back, so I guess it is working.

What am I doing wrong??????
0
 
LVL 9

Expert Comment

by:Venci75
ID: 8259234
are you sure that your mail.jar is ok???
0
 
LVL 9

Expert Comment

by:Venci75
ID: 8259340
try this:
open your jar file as ZIP archive.
Check whether /META-INF/javamail.providers file exists
check whether this entry exists in the file

try this line:
props.put("protocol", "smtp; type=transport; class=com.sun.mail.smtp.SMTPTransport;");

before calling:
Session session = Session.getDefaultInstance(props, null);


0
 
LVL 1

Author Comment

by:dyma82
ID: 8283598
Thanks..!!!
0
 
LVL 9

Expert Comment

by:Venci75
ID: 8283629
??? Was it really a problem with the Authentication? I don't think so
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month7 days, 23 hours left to enroll

615 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question