SMTP Transport: SendFailedException

Currently, our company is in the implementation/testing stage of
several servlets which process sales from internet customers.
One of a servlet's functions is to send a "confirmation / thank you" email
to the customer upon successful credit card verification of purchase.
Our "TransportMail" class ends with an exception after successfully (seemingly,
because "opened" ConnectionEvent is fired) opening a connection to the SMTP
server.
Then, execution is terminated with a SendFailedException. The output of a
test (below the code snippet) shows the result of a System.out of the MimeMessage's methods.
A nested exception states that it could not connect. A process called TCPView shows that the
connection was successful and timed-out on the send(msg).
The test is run from a DOS Prompt.
What's wrong? Why won't the message send?
Thanx much in advance for any suggestions or solutions.
All message values are set properly per the API specs. The message is sent via the following snippet:
Transport tr = session.getTransport("smtp");
tr.addTransportListener(new TransportAdapter() {
public void messageDelivered(TransportEvent e) {System.out.println("\nmessageDelivered: " + e.toString());}
public void messageNotDelivered(TransportEvent e) {System.out.println("\nmessageNotDelivered: " +                                 e.toString());}
public void messagePartiallyDelivered(TransportEvent e) {System.out.println("\nmessagePartiallyDelivered: " +                                      e.toString());}
tr.addConnectionListener(new ConnectionAdapter() {
     public void closed(ConnectionEvent e) {System.out.println("\nclosed: " + e.toString());}
     public void disconnected(ConnectionEvent e) {System.out.println("\ndisconnected: " + e.toString());}
     public void opened(ConnectionEvent e) {System.out.println("\nopened: " + e.toString());}
tr.connect(     "<smtp server>",
          -1,
          "<user id>",
          "<password">     );
tr.send(msg);          // executes msg.saveChanges() prior to send (per API specs)
tr.close();          
C:\TEMP\test>java testSendMail [email protected] BMSCreditMgr
fromaddr= [email protected]
toaddr= [email protected]
msg.getFrom= [email protected]
msg.getAllRecipients= [email protected]
msg.getSubject= Thank you for ordering BMSCreditMgr !
msg.getSentDate= Wed Jan 21 14:37:14 PST 2004
thisMessage= Business Management Systems, Inc. is developing many more
software packages that will enable the individual investor to
manage their investments and make money with their hard-earned dollars.
It is hoped that you find BMSCreditMgr to be a very useful product and that
you make money with it.
Again, thank you very much for your purchase.
opened: javax.mail.event.ConnectionEvent[source=smtp://bmstahoe%[email protected]]
SendFailedException :javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: 530 authentication required - for help go to http://help.yahoo.com/help/us/sbc/dsl/mail/pop/pop-11.html
C:\TEMP\test>

Your conclusion seems to be correct, however, I send many emails (10-20) daily via either Netscape or IE6 with the exact same SMTP server, UserID, and password. Also, other office personnel send emails via Netscape or IE through our LAN using the exact same server, uid, and password.
The code snippet of the TransportMail class (see original) uses the exact same server, uid, and password. A freeware program called TCPView that runs as a process during testing shows that the object connects to port 25 of the server (as expected) and the 'opened' ConnectionEvent is fired (see output in original). The SendMailException has a nested exception saying that it can't connect or sometimes authentication required followed by an additional nested exception: java.net.ConnectException: Connection timed out: connect.
So, if the 'opened' ConnectionEvent is fired and a ConnectException indicates a timeout for the connection, such conditions seem to indicate that a connection was made. The MessagingException stating that authentication is required no longer occurs since the password parm is passed via tr.connect.
I was thinking that maybe the server is possibly attempting to prompt for password instead of taking the password from the program. That might explain why the connection holds for about 20 secs before timeout. I could test that theory with a dialog.

Similar Messages

  • SMTP: Transport.send() works, transport.sendMessage() not ("not connected")

    Sendig a SMTP Message to a running SMTP Server on localhost, port 25 works fine, if i use
    Transport.send( myMessage);However, it does not when i use
    Transport tr = session.getTransport(..);
    tr.connect("localhost", 25, "user", "pass");
    tr.sendMessage ( myMessage );In this case, the connect seems to work (actually, debugging in eclipse has shown that the Transport-internal field "connected" is set to true!), but sending myMessage throws the following Exception:
    java.lang.IllegalStateException: Not connected
         at com.sun.mail.smtp.SMTPTransport.checkConnected SMTPTransport.java:1398)
         at com.sun.mail.smtp.SMTPTransport.sendMessage SMTPTransport.java:489)calling transport.isConnected() also returnsfalseWell, using the static way is a first workaround, that i don't want to use because of the bad performance (need to send lot of mails under certain circumstances).
    Does anyone have an idea whats wrong?

    If your SMTP server does not require authentication, do not use "Transport.connect(server, port, username, password)", use "Transport.connect()" instead.
    If you SMTP server does require authentication, you should have the "mail.smtp.auth" property of the session set as "true".
    The following code is working properly on my machine.
    import java.lang.*;
    import java.util.*;
    import javax.mail.*;
    import javax.mail.event.*;
    import javax.mail.internet.*;
    public class SendMail {
    static String mailHost = "mail.mydomain.com";
    static String source = "[email protected]";
    static String subject = "Test JavaMail";
    static String content = "Content";
    public static void main(String args[]) {
    Properties properties = new Properties();
    properties.put("mail.smtp.host", mailHost);
    properties.put("mail.from", source);
    Session session = Session.getInstance(properties, null);
    try {
    Message message = new MimeMessage(session);
    InternetAddress[] address = new InternetAddress[args.length];
    for (int i = 0; i < args.length; i++)
    address[i] = new InternetAddress(args);
    message.setRecipients(Message.RecipientType.TO, address);
    message.setFrom(new InternetAddress(source));
    message.setSubject(subject);
    message.setContent(content, "text/plain");
    Transport transport = session.getTransport(address[0]);
    transport.addConnectionListener(new ConnectionHandler());
    transport.addTransportListener(new TransportHandler());
    transport.connect();
    transport.sendMessage(message, address);
    } catch (Exception e) {
    System.out.println(e.toString());
    class ConnectionHandler extends ConnectionAdapter {
    public void opened(ConnectionEvent e) {
    System.out.println("Connection opened.");
    public void disconnected(ConnectionEvent e) {
    System.out.println("Connection disconnected.");
    public void closed(ConnectionEvent e) {
    System.out.println("Connection closed.");
    class TransportHandler extends TransportAdapter {
    public void messageDelivered(TransportEvent e) {
    System.out.println("Message delivered.");
    public void messageNotDelivered(TransportEvent e) {
    System.out.println("Message NOT delivered.");
    public void messagePartialDelivered(TransportEvent e) {
    System.out.println("Message partially delivered.");

  • Can OpenMQ use SMTP as transport in a distributed setup?

    Hello all,
    I am researching the usability of OpenMQ to provide messaging services to a number of J2EE
    servers and clients distributed in a multi-segmented network (like central office and branch offices).
    Deployment in each network segment is complete and looks like any other segment's deployment -
    they all have GlassFish app servers, database and LDAP replicas, etc. We plan to connect some
    GlassFish-deployed applications and user-interface clients with MQ services, with a broker and
    each queue's instance deployed in each network segment.
    So my first short question is: am I correct to assume that in order for OpenMQ instances to
    pass messages between clients in different network segments, all of these instances should
    be pre-configured as a single "conventional cluster"? Is this the only way? That is, there is no
    such loose coupling as in email services "I've got a (spam) message for a random recipient
    name, try to deliver it please"?
    Second, can this be implemented as a multi-tier cluster? That is, "home brokers" in different
    network segments are inter-connected as a conventional cluster (brokers with dedicated
    datastores), but in fact these "home brokers" within a network segment are implemented
    as an active-active cluster with a shared datastore (local to the segment). Can this be done?
    Third, hard and titular question is: some of the network segments have no online IP
    connection per system design, they are physically separated. There is a means of
    SMTP transport between nodes in these segments, using offline techniques, though.
    Can OpenMQ nodes exchange messages (client traffic and/or administrative traffic
    like cluster config propagation), using SMTP/POP3/IMAP instead of online connections
    such as JMS/TCP or HTTP?
    I have not found any indication of this approach in the documentation, except that GlassFish
    appservers seem to be able to implement JAX-WS over SMTP as experimentally supported.
    Thanks,
    //Jim

    Hamper wrote:
    I was wondering then, as I don't have a Time Capsule, whether it would be possible to dedicate the second HDD for exclusive use of Time Machine, backing everything up?
    Anyway, would splitting the two work and would it be easily achievable with existing tools in OS X?
    Yes, you can use the 2nd HDD with Time Machine as your TM back up drive.
    As long as you are able to format your new SSD and the HDD, you can use them independently. I would advise using Terminal and the diskutil commands to do this as Mountain Lion 10.8.3's GUI Disk Utility will see the SSD and HDD as needing to be "fixed" (drives marked in RED) and if you choose to FIX the drives your two drives will automatically be setup as a Fusion drive and all data on the drives will be lost.

  • Using SMTP should I get an Exception for wrong recipitients?

    Hi,
    I'm testing JavaMail 1.3.2.
    Once I give a fake recipitients, in the TO address, my email is posted correctly.
    I have tried with severals SMTP server and I get any error.
    I don't remember, if I should get an exception like SendFailedException.
    I attach the code, I use for this test.
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Message;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.event.TransportEvent;
    import javax.mail.event.TransportListener;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Message;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.event.TransportEvent;
    import javax.mail.event.TransportListener;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    public class MailExample implements TransportListener {
         public MailExample() {
              super();
         public void test() throws Exception {
              // Get system properties
              Properties props = System.getProperties();
              // Setup mail server
              props.put("mail.smtp.host", <SMTP_SERVER>);
              // Get session
              Session session = Session.getInstance(props, null);
              session.setDebug(true);
              // Define message
              MimeMessage message = new MimeMessage(session);
              message.setFrom(new InternetAddress(<SENDER_ADDRESS>));
              message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
                        ""+new Date().getTime()+"@thisisnotarealaddressihope.com", false));
              message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(
                        <BCC_ADDRESS>, false));
              message.setHeader("X-Mailer", "JavaMail API");
              message.setSentDate(new Date());
              message.setSubject("Hello JavaMail");
              message.setText("Welcome to JavaMail");
              // Send message
              Transport transport = session.getTransport("smtp");
              transport.connect();
              transport.addTransportListener(this);
              transport.sendMessage(message, message.getAllRecipients());
              transport.close();
              System.out.println("\nMail was sent successfully.");
         public static void main(String[] args) throws Exception {
              MailExample example = new MailExample();
              example.test();
          * (non-Javadoc)
          * @see javax.mail.event.TransportListener#messageDelivered(javax.mail.event.TransportEvent)
         public void messageDelivered(TransportEvent arg0) {
              System.out.println("messageDelivered");
          * (non-Javadoc)
          * @see javax.mail.event.TransportListener#messageNotDelivered(javax.mail.event.TransportEvent)
         public void messageNotDelivered(TransportEvent arg0) {
              System.out.println("messageNotDelivered");
          * (non-Javadoc)
          * @see javax.mail.event.TransportListener#messagePartiallyDelivered(javax.mail.event.TransportEvent)
         public void messagePartiallyDelivered(TransportEvent arg0) {
              System.out.println("messagePartiallyDelivered");
      Regards,
    Manu

    I agree with japamac.
    If you're happy with your Quad G5 and don't plan to upgrade software any time soon, then that is the more economical option. Mini's are great, but I'd say a G5 is more flexible and likely faster and more powerful after you upgrade. I just upgraded the old memory in my dual G5 (from OWC) and that alone has given me a slight speed boost and definitely a stability boost. Can I assume you are planning to use the SSD as a boot disk with your OS and core programs, and a secondary HD as storge for your files?
    http://eshop.macsales.com/shop/SSD/OWC/Mercury_6G/
    http://eshop.macsales.com/shop/SSD/PCIe/OWC/Mercury_Accelsior/RAID
    For what it's worth, I've heard good things about Momentus hybrid drives as well. Nearly the performace of a SSD, with more storage and a lower price tag. I can't speak to compatibility with your system though.
    http://www.seagate.com/internal-hard-drives/laptop-hard-drives/momentus-xt-hybri d/
    Message was edited by: Kort

  • Javax.mail.SendFailedException: Recipient unknown

    Hi,
    I know similar topics have been posted before but even after going through them all I have still not found a solution.
    I am trying to send alert emails through my JavaMail application and get the Exception below. I am able to send emails to internal address', but not external address' such as my hotmail account. I have even asked the Administrator to put my IP address in the list of allowed IP's. Does anyone have any ideas? If anyone would like to take a look at the source code i have pasted it underneath the stacktrace.
    Thanks in advance.
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.SendFailedException: Invalid Addresses;
    nested exception is:
    javax.mail.SendFailedException: 550 <[email protected]>, Recipient unknown
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.SendFailedException: Invalid Addresses;
    nested exception is:
    javax.mail.SendFailedException: 550 <[email protected]>, Recipient unknown
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at Test1.main(Test1.java:28)
    SOURCE:
    import javax.mail.internet.*;
    import javax.activation.*;
    final public class Test1 {
    private static Session session;
    public static void main(String[] args)
         try
              Properties props = new Properties();
              props.put ("mail.smtp.host", "207.132.45.5");
              props.put ("mail.smtp.port", "25");
              session = Session.getInstance(props, null);
              MimeMessage message = new MimeMessage(session);
              message.setFrom (new InternetAddress ("[email protected]"));
              message.setRecipient (Message.RecipientType.TO, new InternetAddress ("[email protected]"));
              message.setSubject ("test message");
              Multipart multipart = new MimeMultipart();
              BodyPart messageBodyPart = new MimeBodyPart();
              multipart.addBodyPart (messageBodyPart);
              messageBodyPart.setText ("message body");
              message.setContent (multipart);
              javax.mail.Transport.send (message);
         } catch (Exception e) {
              System.out.println (e.toString());
              e.printStackTrace();

    Personal, I am sending a class example that uses authentication in the email sending:
    * Class JAVA
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    import java.lang.*;
    import java.lang.Exception;
    public class email
    public void sendSimpleMail (String mailServer, String subject,String to,String from, String mensagem)
    throws AddressException , MessagingException
    Properties mailProps = System.getProperties();
    mailProps.put("mail.smtp.host", mailServer);
    mailProps.put("port","25");
    mailProps.put("mail.smtp.auth", "true");
    Session mailSession = Session.getDefaultInstance(mailProps, new MyPasswordAuthenticator("username", "password"));
    InternetAddress destinatario = new InternetAddress (to);
    InternetAddress remetente = new InternetAddress (from);
    Message message = new MimeMessage (mailSession);
    message.setFrom(remetente);
    message.setRecipient( Message.RecipientType.TO, destinatario );
    message.setSubject (subject);
    message.setContent (mensagem.toString(), "text/plain");
    try
    Transport transport = mailSession.getTransport("smtp");
    transport.connect(mailServer," ", " ");
    transport.send(message);
    catch (javax.mail.SendFailedException sfe)
    System.out.println("FALHA: " + sfe);
    catch (MessagingException e)
    System.out.println("erro: " + e);
    /** This is the authenticator for SMTP session */
    public static class MyPasswordAuthenticator extends Authenticator
    private String username = null;
    private String password = null;
    public MyPasswordAuthenticator(String username, String password)
    super();
    this.username = username;
    this.password = password;
    public PasswordAuthentication getPasswordAuthentication()
    return new PasswordAuthentication(username, password);
    * File JSP
    <html>
    <body>
    <%@ page import="email, javax.mail.*, javax.mail.internet.*, java.util.*" %>
    <jsp:useBean id="email" scope="session" class="email"/>
    <%
    try
    String mailServer = "myServer";
    String assunto = request.getParameter("assunto");
    String para = request.getParameter("para");
    String de = request.getParameter("de");
    String mensagem =request.getParameter("mensagem");
    email.sendSimpleMail(mailServer, assunto, para, de, mensagem);
    %>
    <p>Email enviado com Sucesso !!!</p>
    <%
    catch (AddressException e)
    %> <p>Endereco de Email invalido</p><%
    catch (MessagingException e)
    %> <p>Impossivel enviar o email.</p><%
    %>
    </body>
    </html>

  • Email sending Problem:smtps---SSL---TLS??

    Hi,
    I Have a Problem bei Sending a email with Attachement from extranet, I have writting my Programm which will send my email Through TLS, with Thunderbird
    I can sending there alle emails through TLS, I have taking the seem Properties :
    emai Server Name, Protocol:smtp port:25 und througt TLS, so Now I will show you my Code und the compile Failure, I appreciate so much your Help, I don't find any Help here in Forum.
    My Code:
    public void sendAttachment(String ausgangsMailServer, String user, String password,String sender, String receiver, String filename) throws MessagingException{
              Properties properties = System.getProperties();          
              properties.put("mail.transport.protocol","smtps");
              properties.put("mail.smtps.ssl", "true");
              properties.put("mail.smtps.starttls.enable","true");
              properties.put("mail.smtps.auth", "true");
              properties.put("mail.smtps.debug", "true");
              properties.put("mail.smtps.socketFactory.port", "25");
              properties.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
              properties.put("mail.smtps.socketFactory.fallback", "false");
    SecurityManager security = System.getSecurityManager();
              Session session = Session.getInstance(properties, new MailAuthenticator());                         
              Transport transport = session.getTransport("smtps");                    
              transport.connect(ausgangsMailServer, user, password);          
              Message message = getMessage(session, sender, receiver,filename);
              message.saveChanges();
              transport.sendMessage(message, message.getAllRecipients());          
              transport.close();
         public Message getMessage(Session session, String sender, String receiver, String filename) throws MessagingException{          
         Message message = new MimeMessage(session);                                                                                                                   
    message.setSubject("attachment");
         message.setFrom(new InternetAddress(sender));
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
         Multipart multipart = new MimeMultipart();
         BodyPart bp = new MimeBodyPart();
         bp.setText("Attachment Mail");
         multipart.addBodyPart(bp);
         bp = new MimeBodyPart();
         DataSource source = new FileDataSource(filename);
         bp.setDataHandler(new DataHandler(source));
         bp.setFileName(filename);     
         multipart.addBodyPart(bp);
         message.setContent(multipart);                              
         return message;
         public class MailAuthenticator extends Authenticator{
              public MailAuthenticator(){
              public PasswordAuthentication getPasswordAuthentication(){
                   return new PasswordAuthentication("radouane","mypaaword");
    And I call the methode sendAttachment in a EJB Methode I Use Jboss als Server in my web application.
    This is now my failure:
    05:07:21,382 INFO [STDOUT] javax.mail.NoSuchProviderException: smtps
    05:07:21,382 INFO [STDOUT] at javax.mail.Session.getService(Session.java:76
    4)
    05:07:21,382 INFO [STDOUT] at javax.mail.Session.getTransport(Session.java:
    689)
    05:07:21,382 INFO [STDOUT] at javax.mail.Session.getTransport(Session.java:
    632)
    05:07:21,382 INFO [STDOUT] at javax.mail.Session.getTransport(Session.java:
    612)
    I have Using a smtps protocol , by using smtp I Had this Failure:
    14:15:11,164 INFO [STDOUT] javax.mail.MessagingException: Exception reading res
    ponse;
    nested exception is:
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connecti
    on?
    14:15:11,164 INFO [STDOUT] at com.sun.mail.smtp.SMTPTransport.readServerRes
    ponse(SMTPTransport.java:1090)
    14:15:11,164 INFO [STDOUT] at com.sun.mail.smtp.SMTPTransport.openServer(SM
    TPTransport.java:986)
    14:15:11,164 INFO [STDOUT] at com.sun.mail.smtp.SMTPTransport.protocolConne
    ct(SMTPTransport.java:197)
    14:15:11,164 INFO [STDOUT] at javax.mail.Service.connect(Service.java:233)
    14:15:11,164 INFO [STDOUT] at javax.mail.Service.connect(Service.java:134)
    For your help I say Thanks.
    Radouane

    Hi,
    I want just writtefor you my javamail debug Infomationen by J2SE Application and bei J2EE application. By j2se was that sending successful, by j2ee application is a problem by TSL.
    Hier Debug for j2se application:
    DEBUG: setDebug: JavaMail version 1.4ea
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsys
    tems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host "mail.cs.tu-berlin.de", port 25, isSSL false
    220 mailhost.cs.tu-berlin.de ESMTP Postfix
    DEBUG SMTP: connected to host "mail.cs.tu-berlin.de", port: 25
    EHLO meknes
    250-mailhost.cs.tu-berlin.de
    250-PIPELINING
    250-SIZE
    250-VRFY
    250-ETRN
    250-STARTTLS
    250-ENHANCEDSTATUSCODES
    250 8BITMIME
    DEBUG SMTP: Found extension "PIPELINING", arg ""
    DEBUG SMTP: Found extension "SIZE", arg ""
    DEBUG SMTP: Found extension "VRFY", arg ""
    DEBUG SMTP: Found extension "ETRN", arg ""
    DEBUG SMTP: Found extension "STARTTLS", arg ""
    DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    STARTTLS
    220 2.0.0 Ready to start TLS
    EHLO meknes
    250-mailhost.cs.tu-berlin.de
    250-PIPELINING
    250-SIZE
    250-VRFY
    250-ETRN
    250-AUTH PLAIN LOGIN
    250-ENHANCEDSTATUSCODES
    250 8BITMIME
    DEBUG SMTP: Found extension "PIPELINING", arg ""
    DEBUG SMTP: Found extension "SIZE", arg ""
    DEBUG SMTP: Found extension "VRFY", arg ""
    DEBUG SMTP: Found extension "ETRN", arg ""
    DEBUG SMTP: Found extension "AUTH", arg "PLAIN LOGIN"
    DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    DEBUG SMTP: Attempt to authenticate
    AUTH LOGIN
    334 oioohbzfavsa7
    mnhgvas8799800U=
    30987hasabhsasa6
    Y2hiijsasisas=
    235 2.0.0 Authentication successful
    DEBUG SMTP: use8bit false
    MAIL FROM:<[email protected]>
    250 2.1.0 Ok
    RCPT TO:<[email protected]>
    250 2.1.5 Ok
    DEBUG SMTP: Verified Addresses
    DEBUG SMTP: [email protected]
    DATA
    354 End data with <CR><LF>.<CR><LF>
    From: [email protected]
    To: [email protected]
    Message-ID: <9971081.01168741860633.JavaMail.radouane@meknes>
    Subject: attachment
    MIME-Version: 1.0
    Content-Type: multipart/mixed;
    boundary="----=_Part_0_25199001.1168741860423"
    ------=_Part_0_25199001.1168741860423
    Content-Type: text/plain; charset=us-ascii
    Content-Transfer-Encoding: 7bit
    Attachment Mail
    ------=_Part_0_25199001.1168741860423
    Content-Type: application/octet-stream; name=filename
    Content-Transfer-Encoding: 7bit
    Content-Disposition: attachment; filename=filename
    Now by J2ee application---I use jboss:
    2007-01-14 03:27:28,769 INFO [STDOUT] DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    2007-01-14 03:27:28,769 INFO [STDOUT] DEBUG SMTP: useEhlo true, useAuth true
    2007-01-14 03:27:28,769 INFO [STDOUT] DEBUG SMTP: trying to connect to host "mail.cs.tu-berlin.de", port 25
    2007-01-14 03:27:28,909 INFO [STDOUT] 220 mailhost.cs.tu-berlin.de ESMTP Postfix
    2007-01-14 03:27:28,909 INFO [STDOUT] DEBUG SMTP: connected to host "mail.cs.tu-berlin.de", port: 25
    2007-01-14 03:27:28,909 INFO [STDOUT] EHLO meknes
    2007-01-14 03:27:28,979 INFO [STDOUT] 250-mailhost.cs.tu-berlin.de
    250-PIPELINING
    250-SIZE
    250-VRFY
    250-ETRN
    250-STARTTLS
    250-ENHANCEDSTATUSCODES
    250 8BITMIME
    2007-01-14 03:27:28,979 INFO [STDOUT] DEBUG SMTP: Found extension "PIPELINING", arg ""
    2007-01-14 03:27:28,979 INFO [STDOUT] DEBUG SMTP: Found extension "SIZE", arg ""
    2007-01-14 03:27:28,979 INFO [STDOUT] DEBUG SMTP: Found extension "VRFY", arg ""
    2007-01-14 03:27:28,979 INFO [STDOUT] DEBUG SMTP: Found extension "ETRN", arg ""
    2007-01-14 03:27:28,979 INFO [STDOUT] DEBUG SMTP: Found extension "STARTTLS", arg ""
    2007-01-14 03:27:28,979 INFO [STDOUT] DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    2007-01-14 03:27:28,979 INFO [STDOUT] DEBUG SMTP: Found extension "8BITMIME", arg ""
    2007-01-14 03:27:28,979 INFO [STDOUT] DEBUG SMTP: use8bit false
    2007-01-14 03:27:28,979 INFO [STDOUT] MAIL FROM:<[email protected]>
    2007-01-14 03:27:29,049 INFO [STDOUT] 250 2.1.0 Ok
    2007-01-14 03:27:29,049 INFO [STDOUT] RCPT TO:<[email protected]>
    2007-01-14 03:27:29,159 INFO [STDOUT] 554 5.7.1 <[email protected]>: Recipient address rejected: Access denied
    2007-01-14 03:27:29,159 INFO [STDOUT] DEBUG SMTP: Invalid Addresses
    2007-01-14 03:27:29,159 INFO [STDOUT] DEBUG SMTP: [email protected]
    2007-01-14 03:27:29,159 INFO [STDOUT] DEBUG SMTP: Sending failed because of invalid destination addresses
    2007-01-14 03:27:29,159 INFO [STDOUT] RSET
    2007-01-14 03:27:29,229 INFO [STDOUT] 250 2.0.0 Ok
    2007-01-14 03:27:29,229 INFO [STDOUT] QUIT
    2007-01-14 03:27:29,229 INFO [STDOUT] Error Sending:
    2007-01-14 03:27:29,229 INFO [STDOUT] Sending failed;
    nested exception is:
         class javax.mail.SendFailedException: Invalid Addresses;
    nested exception is:
         class javax.mail.SendFailedException: 554 5.7.1 <[email protected]>: Recipient address rejected: Access denied
    2007-01-14 03:27:29,229 INFO [STDOUT] java.lang.NullPointerException
    can someone tell me, where is my problem by j2ee application, it's a ejb class -using jboss-.
    Thanks ,
    Radouane
    Message was edited by:
    radouane.marjani

  • SMTP relay works with Thunderbird but not with Javamail

    Hi all,
    I'm really clueless now and decided to ask for help here in this forum.
    I'm trying to send a mail via an SMTP server which needs a login.
    I keep getting the error message
    "javax.mail.SendFailedException: 554 <[email protected]>: Relay access denied"
    I read many postings in this forum which say that the smtp server's config is responsible.
    But that cannot be because I'm able to send mails via the smtp-server when I use the mail client Mozilla-Thunderbird.
    Thunderbird runs on the same computer as my java mail program does.
    Does anyone know how this can be?
    My first guess was that it must be an authentication problem.
    But the following lines work well.
    Transport transport = session.getTransport("smtp");
    transport.connect(host, user, pwd);Maybe I should use the other way of authentication.
    But unfortunately the following code leads to an authentication failure (DEBUG SMTP RCVD: 535 Error: authentication failed).
    Properties props = System.getProperties();
    props.put("mail.MailTransport.protocol", "smtp");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth","true");
    SmtpAuthenticator auth = new SmtpAuthenticator(user, pwd);
    Session session = Session.getDefaultInstance(props, auth);          with
         private class SmtpAuthenticator extends Authenticator {
              private String user = null;
              private String pwd  = null;
              public SmtpAuthenticator(String user, String pwd) {
                   this.user = user;
                   this.pwd = pwd;
              protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication(this.user, this.pwd);
         }Any hints are greatly appreciated.
    Thanks in advance,
    Stefan

    Hi,
    I think it's a good idea to share a most complete view of what I'm doing.
    The smtp server the problem is all about is called h8233.serverkompetenz.net.
    I successfully sent a message to myself using Thunderbird via this server.
    Here's an excerpt from my Thunderbird Inbox file showing that message including all headers.
    From - Wed Jul 28 10:07:16 2004
    X-UIDL: b125a9357a0e8f614916a3ab1a6f9af5
    X-Mozilla-Status: 0001
    X-Mozilla-Status2: 00000000
    Return-Path: <[email protected]>
    X-Flags: 0000
    Delivered-To: GMX delivery to [email protected]
    Received: (qmail 2762 invoked by uid 65534); 28 Jul 2004 08:06:56 -0000
    Received: from unknown (EHLO h8233.serverkompetenz.net) (81.169.187.39)
      by mx0.gmx.net (mx050) with SMTP; 28 Jul 2004 10:06:56 +0200
    Received: from [192.168.0.5] (a81-14-157-170.net-htp.de [81.14.157.170])
         by h8233.serverkompetenz.net (Postfix) with ESMTP id 97D1455C035
         for <[email protected]>; Wed, 28 Jul 2004 10:08:01 +0200 (CEST)
    Message-ID: <[email protected]>
    Date: Wed, 28 Jul 2004 10:07:09 +0200
    From: Stefan Prange <[email protected]>
    User-Agent: Mozilla Thunderbird 0.7.2 (Windows/20040707)
    X-Accept-Language: de-at, en-us
    MIME-Version: 1.0
    To: [email protected]
    Subject: This is the test mail's subject.
    Content-Type: text/plain; charset=us-ascii; format=flowed
    Content-Transfer-Encoding: 7bit
    X-GMX-Antivirus: 0 (no virus found)
    X-GMX-Antispam: 0 (Sender is in whitelist: [email protected])
    This is the test mail's content.And here's the java program I wrote to make JavaMail do excactly the same as Thunderbird does.
              try {
                   String user = "secret";
                   String pwd = "secret";
                   String host = "h8233.serverkompetenz.net";
                   //Prepare session
                   Properties props = System.getProperties();
                   props.put("mail.MailTransport.protocol", "smtp");
                   props.put("mail.smtp.host", host);
                   props.put("mail.smtp.user", user);
                   Session session = Session.getDefaultInstance(props, null);
                   session.setDebug(true);
                   //Prepare message
                   Address from = new InternetAddress("[email protected]", "Stefan Prange");
                   Address to = new InternetAddress("[email protected]");
                   MimeMessage message = new MimeMessage(session);
                   message.setFrom(from);
                   message.setReplyTo(new Address[]{from});
                   message.setRecipient(Message.RecipientType.TO, to);
                   message.setSentDate(new Date());
                   message.setSubject("This is the test mail's subject.");
                   message.setText("This is the test mail's content.");
                   message.saveChanges();
                   //Send message
                   Transport transport = session.getTransport("smtp");
                   transport.connect(host, user, pwd);
                   if (transport.isConnected()) {
                        System.out.println("SUCCESSFULLY CONNECTED to SMTP SERVER");
                        System.out.println();
                   } else {
                        System.out.println("FAILED TO CONNECT to SMTP SERVER");
                        return;
                   transport.sendMessage(message, message.getAllRecipients());
                   transport.close();
              } catch (UnsupportedEncodingException e) {
                   e.printStackTrace();
                   return;
              } catch (NoSuchProviderException e) {
                   e.printStackTrace();
                   return;
              } catch (MessagingException e) {
                   e.printStackTrace();
                   return;
         }As you already know the java program fails.
    Here's its console output.
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth false
    DEBUG: SMTPTransport trying to connect to host "h8233.serverkompetenz.net", port 25
    DEBUG SMTP RCVD: 220 h8233.serverkompetenz.net ESMTP Postfix
    DEBUG: SMTPTransport connected to host "h8233.serverkompetenz.net", port: 25
    DEBUG SMTP SENT: EHLO spnotebook
    DEBUG SMTP RCVD: 250-h8233.serverkompetenz.net
    250-PIPELINING
    250-SIZE 10240000
    250-VRFY
    250-ETRN
    250-AUTH PLAIN LOGIN
    250-AUTH=PLAIN LOGIN
    250 8BITMIME
    DEBUG SMTP Found extension "PIPELINING", arg ""
    DEBUG SMTP Found extension "SIZE", arg "10240000"
    DEBUG SMTP Found extension "VRFY", arg ""
    DEBUG SMTP Found extension "ETRN", arg ""
    DEBUG SMTP Found extension "AUTH", arg "PLAIN LOGIN"
    DEBUG SMTP Found extension "AUTH=PLAIN", arg "LOGIN"
    DEBUG SMTP Found extension "8BITMIME", arg ""
    DEBUG SMTP SENT: NOOP
    DEBUG SMTP RCVD: 250 Ok
    SUCCESSFULLY CONNECTED to SMTP SERVER
    DEBUG SMTP: use8bit false
    DEBUG SMTP SENT: MAIL FROM:<[email protected]>
    DEBUG SMTP RCVD: 250 Ok
    DEBUG SMTP SENT: RCPT TO:<[email protected]>
    DEBUG SMTP RCVD: 554 <[email protected]>: Relay access denied
    Invalid Addresses
      [email protected]
    DEBUG SMTPTransport: Sending failed because of invalid destination addresses
    DEBUG SMTP SENT: RSET
    DEBUG SMTP RCVD: 250 Ok
    javax.mail.SendFailedException: Invalid Addresses;
      nested exception is:
         javax.mail.SendFailedException: 554 <[email protected]>: Relay access denied
         at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:804)
         at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:320)
         at de.zorro.util.test.MailTest.main(MailTest.java:62)I hope I gave a sufficient picture of my problem.
    Does anybody know what's wrong in my java program?
    Stefan

  • Retries and SendFailedException

    If you call getValidUnsentAddresses() on SendFailedException, how can you find out which were part of TO, CC, and BCC? If you weren't able to determine this, then wouldn't the best way to handle a resend be to resend the message to all getValidUnsentAddresses() in the TO line?
    This would not be desirable, so how might this situation be avoided while maintaining the ability to retry the message? How can you find out whether a failed address should be resent as TO, CC, or BCC based on the first attempt of that message?
    Thanks.

    Normally, SendFailedException means the message wasn't sent to any
    recipients and you'll need to retry sending the entire message after
    fixing any problems.
    If you configure the SMTP Transport to allow partial failures, then you
    have a more difficult job handling the failures.
    If you're willing to depend on features specific to Sun's SMTP Transport
    provider, you can get detailed information about each recipient. However,
    you'll still need to compare the addresses that failed with the addresses
    in each recipient list to determine whether the failed address was in the
    TO list or the CC list or the BCC list.

  • Urgent help: why smtp authenticator doesn't work ?

    Please help me :
    My smtp server authenticates me whether a valid user when I send email. I have had setup an authenticator as following :
    //Setup authenticator
    Authenticator auth = new SMTPAuthenticator();
    // Get session
    Session session = Session.getDefaultInstance(props, auth);
    class SMTPAuthenticator extends Authenticator
    public PasswordAuthentication getPasswordAuthentication()
    String username="userid";
    String password="passwd";
    return new PasswordAuthentication(username, password);
    But It still prompted error with noting me:" login fail, this smtp server authentication required ".What's the problem?
    I'm a valid user in this smtp server. and the userid and passwd has no error, for it worked well when I used them to setup win2000 outlook express.
    I also tried to used authenticated javax.mail.Service's connect .
    Transport transport = session.getTransport("smtp");
    transport.connect(smtphost, username, password);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
    but it didn't work yet ! If I use Authenticator ,is it still necessary to use connect(smtphost, username, password) ?
    Urgently, Please help me, any source code practising well with authenticating smtp server , please send it to [email protected]
    Thanks

    Just use " props.put("mail.smtp.auth", "true");"

  • AuthenticationFailedException when using JNDI and JavaMail with SMTP auth

    Hi all - I've been banging my head on this one for awhile now - hopefully someone else has done this.
    We are working in a servlet container (tomcat), and need obtain a mail session from JNDI. We do this as follows:
                   Context initCtx = new InitialContext();
                   Context envCtx = (Context) initCtx.lookup("java:comp/env");
                   Session mailSession=(Session) envCtx.lookup("mailSession/trumpetinc");so far so good. The jndi entry for the mail session is configured in server.xml as follows:
              <Resource name="mailSession/trumpetinc" scope="Shareable" type="javax.mail.Session"/>
              <ResourceParams name="mailSession/trumpetinc">
                <parameter>
                  <name>mail.smtp.host</name>
                  <value>mail.server.com</value>
                </parameter>
                <parameter>
                  <name>mail.smtp.password</name>
                  <value>ABCDEFG</value>
                </parameter>
                <parameter>
                  <name>mail.smtp.user</name>
                  <value>trumpet_kevin</value>
                </parameter>
             <parameter>
               <name>mail.smtp.auth</name>
               <value>true</value>
             </parameter>
              </ResourceParams>With the above, whenever we hit Transport.send(msg), we got an AuthenticationFailedException thrown. I have run into this before with SMTP authentication, so I decided to try using the transport.sendMessage() method instead.
    So, I get the transport:
    Transport trans = mailSession.getTransport("smtp");
    trans.connect();Then I send my message using:
    msg.saveChanges();
    trans.sendMessage(msg, msg.getAllRecipients());and finally, I close the transport:
    trans.close();Unfortunately, I'm still getting the exception. Is it possible that my connect() method is not picking up the JNDI properties set in the server.xml file (this seems likely)? If so, what's the best way for me to get those properties so I can set them explicitly in the connect() method?
    Thanks in advance,
    - Kevin

    Hi,
    I have faced the same problem and after some googling and trying I have discovered what causes the AuthenticationFailedException exception. I just wanted to share the knowedge maybe it will be helpfull to others.
    Here it is what the API says:
    To use SMTP authentication you'll need to set the mail.smtp.auth property (see below) and provide the SMTP Transport with a username and password when connecting to the SMTP server. You can do this using one of the following approaches:
    1.Provide an Authenticator object when creating your mail Session and provide the username and password information during the Authenticator callback.
    Note that the mail.smtp.user property can be set to provide a default username for the callback, but the password will still need to be supplied explicitly.
    This approach allows you to use the static Transport send method to send messages.
    2.Call the Transport connect method explicitly with username and password arguments.
    This approach requires you to explicitly manage a Transport object and use the Transport sendMessage method to send the message. The transport.java demo program demonstrates how to manage a Transport object. The following is roughly equivalent to the static Transport send method, but supplies the needed username and password:
    Using the Transport.connect makes the JNDI not very helpfull for configuration.
    It seems that using just the mail.smtp.user and mail.smtp.pass is not sufficient for the authentication.
    so, the solution is :
    just place these to lines in the JNDI configuration:
              username="test"
              password="test1"
    so it should looks as follows:
              <Resource name="mail/Session" auth="Container"
              type="javax.mail.Session"
              username="test"
              password="test1"
              mail.transport.protocol="smtp"
              mail.smtp.auth="true"     
              mail.smtp.host="localhost"
              mail.smtp.port="25"
              mail.smtp.user="test"
              mail.smtp.password="test1"
    />
    where test and test1 are the user's credentials
    Regards,
    Kiril
    Message was edited by:
    Kireto
    Message was edited by:
    Kireto

  • How to send the same message to two SMTP servers

    hi,
    I need to send a message to two different SMTP servers.
    I want to avoid the creation of new MimeMessage with a new Session.
    the only way I've found was to keep a reference to the Properties instance that was used in the Session creation, and modify its "mail.smtp.host" property.
    Is there another way? I must be missing something.
    thanks,
    ofer

    hi,
    I've already found the solution, so I'll post it here.
    first I'll explain the purpose:
    I needed to send the same message to a normal email server, and (for some of the recipients) to a special SMTP server that is on a different machine.
    the following code demonstrate the solution.
    thanks for your help.
    ofer
    ----------code---------------
    public class MultipleSendTest {
    private final static Session server1 = createSession("somesmtp_server.com");
    private final static Session _server2 = createSession("another_smtp_server.com");
    public static void main(String args[]) throws Exception {
    //create the message
    MimeMessage m = new MimeMessage(_server1);
    m.setText("body text");
    m.addRecipients(Message.RecipientType.TO, "[email protected]");
    m.setFrom(new InternetAddress("[email protected]"));
    //send
    send(m, _server1);
    send(m, _server2);
    private static void send(MimeMessage message, Session session) {
    //for logging only
    String host = session.getProperty("mail.smtp.host");
    try {
    Transport transport = session.getTransport("smtp");
    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    System.out.println("sent to " + host);
    transport.close();
    } catch (MessagingException e) {
    System.out.println("failed to send to " + host);
    private static Session createSession(String host) {
    Properties properties = new Properties();
    properties.setProperty("mail.smtp.host", host);
    return Session.getInstance(properties);
    ----------code---------------

  • Javax.mail.MessagingException: Could not connect to SMTP host:

    here is a part of my code
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    public class Mail {
    /** Creates a new instance of PostMail */
    public Mail() {
    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."_____".com");
    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    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);
    msg.setRecipients(Message.RecipientType.TO, addressTo);
    // Optional : You can also set your custom headers in the Email if you Want
    msg.addHeader("MyHeaderName", "myHeaderValue");
    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
    Here is the exception i rec'vd
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.google.com, port: 25;
    nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
    at javax.mail.Service.connect(Service.java:275)
    at javax.mail.Service.connect(Service.java:156)
    at javax.mail.Service.connect(Service.java:105)
    at javax.mail.Transport.send0(Transport.java:168)
    at javax.mail.Transport.send(Transport.java:98)
    at Mail.postMail(Mail.java:45)
    at ArchMain.<init>(ArchMain.java:30)
    at ArchMain$6.run(ArchMain.java:360)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:519)
    at java.net.Socket.connect(Socket.java:469)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
    ... 17 more

    package MailDao;
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    import java.io.*;
    import java.text.*;
    import java.text.DateFormat.* ;
    import java.io.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.activation.*;
    import javax.mail.search.*;
    import java.util.Vector.*;
    import java.sql.*;
    public class SendMail {
    String SMTP_HOST_NAME = "smtp.techpepstechnology.com";//smtp.genuinepagesonline.com"; //techpepstechnology.com";
    String SMTP_AUTH_USER = "[email protected]"; //[email protected]"; //techpeps";
    String SMTP_AUTH_PWD = "demo"; //techpeps2007";
    public void postMail( String recipients[ ], String subject,
    String message , String from,String msgType) throws MessagingException {
    boolean debug = false;
    Properties props = System.getProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(debug);
    // create a message
    MimeMessage msg = new MimeMessage(session);
    // MimeMessage mimemessage = new MimeMessage(simplemailuser.getSession());
    // 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);
    msg.setRecipients(Message.RecipientType.TO, addressTo);
    // Setting the Subject and Content Type
    msg.setSubject(subject);
    if(msgType.equalsIgnoreCase("")) {
    //mimemessage.setText(s4);
    msg.setContent(message, "text/plain");
    else {
    MimeBodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText(message);
    MimeBodyPart fileBodyPart = new MimeBodyPart();
    FileDataSource fds = new FileDataSource(msgType);
    fileBodyPart.setDataHandler(new DataHandler(fds));
    fileBodyPart.setFileName(fds.getName());
    //step:5 create the multipart/container to hold the part
    Multipart container = new MimeMultipart();
    container.addBodyPart(textBodyPart);
    container.addBodyPart(fileBodyPart);
    //step:6 add the multipart to the actual message
    msg.setContent(container);
    try{
    Transport transport=session.getTransport("smtp");
    transport.connect();
    transport.send(msg);
    transport.close();
    }catch(Exception e) {
    e.printStackTrace();
    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);
    public static void main(String arg[]) {
    SendMail sm = new SendMail();
    String[] s ={"[email protected]"};
    try{
    sm.postMail(s,"hello","This is testing of mail","[email protected]","");
    catch(Exception e)
    e.printStackTrace();
    //sm.sendMsg("demo", "demo");
    System.out.println("Mail Sent");
    i also got the follwing error this code work fine in jcreator but i used this in netbeans it throws a exception
    plz.....help
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.techpepstechnology.com, port: 25;
    nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:867)
    Mail Sent
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:156)
    at javax.mail.Service.connect(Service.java:256)
    at javax.mail.Service.connect(Service.java:135)
    at javax.mail.Service.connect(Service.java:87)
    at com.sun.mail.smtp.SMTPTransport.connect(SMTPTransport.java:93)
    at MailDao.SendMail.postMail(SendMail.java:86)
    at MailDao.SendMail.main(SendMail.java:110)

  • Unable to connect  smtp server

    iam trying to send a mail using javamailAPI
    my code in a jsp is follows
    Properties props = new Properties();
    props.put("mail.smtp.host", xxxxx); //xx is hostname
    Session s = Session.getInstance(props,null);
    MimeMessage message = new MimeMessage(s);
    InternetAddress from = new InternetAddress("[email protected]");
    message.setFrom(from);
    InternetAddress to = new InternetAddress("[email protected]");
    message.addRecipient(Message.RecipientType.TO, to);
    message.setSubject("Test from JavaMail.");
    message.setText("Hello from JavaMail!");
    Transport transport = s.getTransport("smtp");
    transport.connect(host, username,password); // 3 fields are host , username, password
    transport.send(message);
    transport.close();
    but iam getting following error
    class com.sun.mail.smtp.SMTPAddressFailedException: 553 Sorry, that domain isn't in my list of allowed rcpthosts.
    pls any one help me soving this problem
    Any pointers will be greatly
    appreciated.

    Sorry, I must've misunderstood your message.  I thought it was working on Linux.
    Show me how it fails on Linux.  Run telnet, then run your program that fails on the same machine, with debug output to the console.  Copy and paste the entire session here - telnet plus your JavaMail program output.
    Also, try using the smtpsend.java sample program.  That will eliminate your code as a possible source of the problem.

  • Transport connect Hang

    Hello to all, i have developed a very simple mail UI to send email but i encounter error where when the debug pointer reach this statement
    private final static String myHost = "smtp.gmail.com";
    Username is the email address.
    try {
    myTransport.connect(myHost, 587, auth.getUsername(),
    auth.getPassword());
    catch(MessagingException ex) {
    myLogger.log(Level.ALL, ex.toString());
    , the debug pointer is just get disappear and no exception is throw. Therefore, i can't even get any useful log.
    Thanks.
    Edited by: peterwkc on Jun 28, 2011 3:31 AM
    Edited by: peterwkc on Jun 28, 2011 3:35 AM

    I using SSL but i get this exception :
    SEVERE: Mail Exception : javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
         java.net.SocketTimeoutException: Read timed out
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
         java.net.SocketTimeoutException: Read timed out
    This is my code :
    // Register Java Secure Socket Extensio(JSSE) provider
    Provider mySecureProvider = new Provider();
    Security.addProvider(mySecureProvider);
    mailProperties = new Properties();
    mailProperties.put("mail.smtp.auth", "true");
    mailProperties.put("mail.smtp.host", myHost);
    mailProperties.put("mail.smtp.port", myPort);
    // mailProperties.put("mail.smtp.starttls.enable", "true");
    mailProperties.put("mail.smtp.timeout", timeOut);
    mailProperties.put("mail.smtp.connectiontimeout", timeOut);
    // mailProperties.put("mail.smtp.ssl.trust", myHost);
    mailProperties.put("mail.smtp.socketFactory.port", myPort);
    mailProperties.put("mail.smtp.socketFactory.class", sslFactory);
    mailProperties.put("mail.smtp.socketFactory.fallback", "false");
    mailProperties.put("mail.debug", true);
    mailSession = Session.getInstance(mailProperties, theAuthenticator);
    mailSession.setDebug(true);
    mailMessage = new MimeMessage(mailSession);
    public static MyMail createInstance(MyAuthenticator theAuthenticator) {
    if(myMailInstance == null) {
    myMailInstance = new MyMail(theAuthenticator);
    return myMailInstance;
    public void sendMessagage(MessageAttribute myMsgAttribute,
    MyAuthenticator auth) {
    try {
    mailMessage.setSentDate(new Date());
    mailMessage.setSubject(myMsgAttribute.getSubject());
    mailMessage.setFrom(myMsgAttribute.getFrom());
    mailMessage.setRecipient(Message.RecipientType.TO,
    myMsgAttribute.getRecipient());
    mailMessage.setContent(myMsgAttribute.getMsgContent(),
    "text/plain");
    //<editor-fold defaultstate="collapsed" desc="TLS">
    /*try {
    * // Get transport protocol
    * // Recommend not to use smtp transport directly but
    * // use mail session to get the transport
    * Transport myTransport = mailSession.getTransport("smtp");
    * try {
    * myTransport.connect(myHost, myPort, auth.getUsername(),
    * auth.getPassword());
    * catch(MessagingException ex) {
    * myLogger.log(Level.SEVERE, ex.toString());
    * if(myTransport.isConnected()) {
    * Address[] recipientAddress = new InternetAddress[1];
    * recipientAddress[0] = myMsgAttribute.getRecipient();
    * mailMessage.saveChanges();
    * myTransport.sendMessage(mailMessage, recipientAddress);
    * myTransport.close();
    * Logger.getLogger(MyMail.class.getName()).log(Level.SEVERE,
    * "Mail Log : " + "Mail sent");
    * else {
    * Logger.getLogger(MyMail.class.getName()).log(Level.SEVERE,
    * "Mail Exception : " + "Mail Server cannot be connect");
    * catch(NoSuchProviderException ex) {
    * Logger.getLogger(MyMail.class.getName()).log(Level.SEVERE,
    * "Mail Exception : " + ex.toString(), ex);
    //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc="SSL">
    //</editor-fold>
    Transport.send(mailMessage);
    catch (MessagingException ex) {
    Logger.getLogger(MyMail.class.getName()).log(Level.SEVERE,
    "Mail Exception : " + ex.toString(), ex);
    Please help.
    Thanks.
    Edited by: peterwkc on Jul 4, 2011 11:46 PM

  • How to register own Transport implementation inside java

    Hi,
    My application is running on a shared host where I do not have admin rights.
    I have written my own implementation of the SMTP Transport.
    In order to be able to use it, it appears that I have to register it in
    $JAVA_HOME/jre/lib/javamail.providers
    with the line
    protocol=smtp_my; type=transport; class=com.my.app.mail.SMTPTransportMy; vendor=Me;
    this, is however not possible in all environments I want to run my app.
    Is there a way to do it inside java similar to the MailcapCommandMap approach?
    Any hints would be highly appreciated!
    Ralf
    https://www.privasphere.com/e.do?email=hauser(at)acm.org
    Just for reference how it is done there!
    MailcapCommandMap mc = (MailcapCommandMap) CommandMap
    .getDefaultCommandMap();
    mc .addMailcap("text/enriched;;x-java-content-handler=com.sun.mail.handlers.text_plain");
    //.addMailcap("text/*;;x-java-content-handler=com.sun.mail.handlers.text_plain");
    CommandMap.setDefaultCommandMap(mc);

    I don't understand what you mean by register a bean inside another bean.

Maybe you are looking for