Solved

JavaMail SMTP Send Mail : MAIL requires AUTH

Posted on 2004-09-16
18
32,457 Views
Last Modified: 2013-11-24
Hi all,

I am using open-source servlet to send email via SMTP. But the SMTP gateway requires authentication. Following is the error message :-

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 "smtp1.host.com", port 25

DEBUG SMTP RCVD: 220 mail1.host.com ESMTP Mirapoint 3.4.4-GR; Thu, 16 Sep 2004 17:49:19 +0800 (MYT)

DEBUG: SMTPTransport connected to host "smtp1.host.com", port: 25

DEBUG SMTP SENT: EHLO MYNAME
DEBUG SMTP RCVD: 250-mail1.host.com Hello MYNAME.host.com [1xx.1xx.2xx.2xx], pleased to meet you
250-8BITMIME
250-SIZE 13500000
250-DSN
250-ETRN
250-STARTTLS
250 HELP

DEBUG SMTP Found extension "8BITMIME", arg ""
DEBUG SMTP Found extension "SIZE", arg "13500000"
DEBUG SMTP Found extension "DSN", arg ""
DEBUG SMTP Found extension "ETRN", arg ""
DEBUG SMTP Found extension "STARTTLS", arg ""
DEBUG SMTP Found extension "HELP", arg ""
DEBUG SMTP: use8bit false
DEBUG SMTP SENT: MAIL FROM:<eddie.see@host.com>
DEBUG SMTP RCVD: 530 <eddie.see@host.com>... MAIL requires AUTH

Messaging exception: 530 <eddie.see@host.com>... MAIL requires AUTH

==> How can I enable the servlet to send email via SMTP using authentication? The SMTP Gateway is "smtp1.host.com" but it seems to be re-routed to "mail1.host.com".


My source code is as follow:-

package com.elucify.tips.oct2002;

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.servlet.http.*;
import javax.servlet.*;

public class SendmailServlet extends HttpServlet {
    protected ServletConfig _config;
    protected Session _mailSession;
    protected String _mailhost;
    protected String _mailuser;
    protected boolean _debug;

    public SendmailServlet() {
        _config = null;
        _mailSession = null;
        _mailhost = null;
        _mailuser = null;
    }

    public void init(ServletConfig config) {
        _config = config;
        _mailhost = config.getInitParameter("mailhost");
        _mailuser = config.getInitParameter("mailuser");
    }

    // doGet and doPost do the same thing
    public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException {
        doService(req, res);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException {
        doService(req, res);
    }

    protected void doService(HttpServletRequest req,
                             HttpServletResponse res)
        throws IOException, ServletException {

        res.setContentType("text/html");

        // Get (or create and cache) mail session
        Session s = getMailSession();

        // If either init parameter or request
        // parameter "debug" is set, output
        // SMTP session log to server log.
        boolean debug = false;
        String sdebug = _config.getInitParameter("debug");

        if (sdebug == null) {
            sdebug = req.getParameter("debug");
        }

        if (sdebug != null &&
            Boolean.valueOf(sdebug).booleanValue()) {
            s.setDebug(true);
        }

        // Create new message
        MimeMessage msg = new MimeMessage(s);

        // Put data from request into message
        try {
            String messageText =
                req.getParameter("messagetext");
            msg.setText(messageText);

            String subject = req.getParameter("subject");
            if (subject != null) {
                msg.setSubject(subject);
            }


                String password = req.getParameter("pwd");
            String addrFrom =
                req.getParameter("addrfrom");
            String nameFrom =
                req.getParameter("namefrom");
            Address fromAddr =
                new InternetAddress(addrFrom, nameFrom);
            msg.setFrom(fromAddr);
            String addrto = req.getParameter("addrto");
            String nameto = req.getParameter("nameto");
            Address toAddr =
                new InternetAddress(addrto, nameto);
            msg.addRecipient(Message.RecipientType.TO, toAddr);

            // Send the message
            //Transport.send(msg);
                Transport tr = _mailSession.getTransport("smtp");
                tr.connect(_mailhost, _mailuser, password);
                msg.saveChanges();
                tr.sendMessage(msg, msg.getAllRecipients());
                tr.close();

            // Print a message acknowledging that the message
            // was sent
            PrintWriter pw = res.getWriter();
            res.setContentType("text/html");
            pw.println("<HTML><BODY>Email sent" +
                       "</BODY></HTML>");

        } catch (UnsupportedEncodingException e) {
            System.err.println("Unsupported encoding: " +
                               e.getMessage());
        } catch (MessagingException m) {
            System.err.println("Messaging exception: " +
                               m.getMessage());
        }

     }

    // Open the mail session if it isn't already open.
    protected Session getMailSession()
      throws ServletException {

        // Throw exception if mail host or user are not set
        if (_mailhost == null || _mailuser == null) {
            throw new ServletException("SendmailServlet " +
              "init parameters mailhost and mailuser must " +
              "both be set in deployment descriptor");
        }

        // Create mail session if it doesn't exist
        if (_mailSession == null) {
            Properties p = new Properties();
            p.put("mail.host", _mailhost);
            p.put("mail.user", _mailuser);
            p.put("mail.smtp.auth", "true");

            // Can define and initialize other session
            // properties here, if desired
            _mailSession = Session.getDefaultInstance(p, null);
        }
        return _mailSession;
    }

}



Please help.
Eddie
0
Comment
Question by:eddie81
  • 4
  • 3
  • 3
  • +2
18 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 12073373
what happens if you try to connect straight to

   mail1.host.com

instead of

    smtp1.host.com

?
0
 
LVL 35

Expert Comment

by:TimYates
ID: 12073374
I guess you may get relay errors then :-(
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12073901
>>  _mailSession = Session.getDefaultInstance(p, null);

You're passing null - you should be passing an Authenticator instance
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12074001
_mailSession = Session.getDefaultInstance(p, new Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
            return PasswordAuthentication("username", "password");
      }
});
0
 
LVL 1

Expert Comment

by:achilka
ID: 12077438
change line from
            p.put("mail.host", _mailhost);

to
p.put("mail.smtp.host",_mailhost);

....
after msg.addRecipient(.....
add this
BodyPart messageBodyPart = new MimeBodyPart();
            // Fill the message
            messageBodyPart.setText(bodystr);
            messageBodyPart.setHeader("Content-Type", "text/html");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
 // Put parts in message
            message.setContent(multipart);

            // Send the message
            Transport.send(message);

and just send it....comment out
*****
Transport tr = sms._mailSession.getTransport("smtp");
            tr.connect(sms._mailhost, sms._mailuser, password);
            msg.saveChanges();
            tr.sendMessage(msg, msg.getAllRecipients());
            tr.close();
******
0
 

Author Comment

by:eddie81
ID: 12081767
Dear achilka,

I have made the necessary changes as adviced by you (javac OK) but I still have the same "MAIL requires AUTH" error.

Dear CEHJ,

When I replace "_mailSession = Session.getDefaultInstance(p, null);" with the following lines, I can't even compile the java file

_mailSession = Session.getDefaultInstance(p, new Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
          return PasswordAuthentication(_mailuser, password);
     }
});

The error message :-

javac SendmailServlet.java
SendmailServlet.java:163: reference to Authenticator is ambiguous, both class java.net.Authenticator in java.net and class javax.mail.Authenticator in javax.mail match
        _mailSession = Session.getDefaultInstance(p, new Authenticator() {
                                                         ^
SendmailServlet.java:164: reference to PasswordAuthentication is ambiguous, both class java.net.PasswordAuthentication in java.net and class javax.mail.PasswordAuthentication in javax.mail match
     protected PasswordAuthentication getPasswordAuthentication() {
               ^
SendmailServlet.java:165: cannot resolve symbol
symbol: variable password
          return PasswordAuthentication(_mailuser, password);
                                                   ^
SendmailServlet.java:163: cannot resolve symbol
symbol  : method getDefaultInstance (java.util.Properties,<anonymous java.net.Authenticator>)
location: class javax.mail.Session
        _mailSession = Session.getDefaultInstance(p, new Authenticator() {
                              ^
4 errors
0
 
LVL 35

Expert Comment

by:TimYates
ID: 12082204
_mailSession = Session.getDefaultInstance(p, new java.mail.Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
          return PasswordAuthentication(_mailuser, password);
     }
});

and you will need to pass password to your getMailSession method...
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:eddie81
ID: 12082366
I have just asked my mail server administrator and he said SSL is required to send out-going email.

How can I do so?
0
 

Author Comment

by:eddie81
ID: 12082541
How can I send email using SMTP protocal with SSL via Javamail?

Any source code will be appreciated.
Eddie
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 125 total points
ID: 12082581
It's probably got a bit easier than this since this was written, but:

http://www.javaworld.com/javatips/jw-javatip115.html
0
 
LVL 1

Expert Comment

by:achilka
ID: 12206328
Properties p = new Properties();
                      p.put("mail.smtp.host", "smtp.domain.com");
                      p.put("mail.smtp.user", username);
                        p.put("mail.smtp.password", password);
                      p.put("mail.smtp.auth", "true");


          Session _mailSession = Session.getDefaultInstance(p, new Authenticator() {
               protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
//if on intranet use intranet username and password check with mail admin
               }
          });
          // Create new message
          MimeMessage message = new MimeMessage(_mailSession);
          Address fromAddr =
                          new InternetAddress(".com", "Name");
                      message.setFrom(fromAddr);

                      Address toAddr =
                          new InternetAddress(to, toname);
                      message.addRecipient(Message.RecipientType.TO, toAddr);

          BodyPart messageBodyPart = new MimeBodyPart();
                      // Fill the message
                      messageBodyPart.setText("hello.............");
                      messageBodyPart.setHeader("Content-Type", "text/html");
                      Multipart multipart = new MimeMultipart();
                      multipart.addBodyPart(messageBodyPart);
           // Put parts in message
                      message.setContent(multipart);

                      // Send the message
                      Transport.send(message);
0
 
LVL 1

Expert Comment

by:achilka
ID: 12206332
Merge the above piece of code into you servlet ...it should work...if it doesn't then check your username and password...Cheers!!!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12402024
Seems a fair bet that if there are authentication errors and the questioner is not using an Authenticator, the solution is per my comments ;-)
0
 

Expert Comment

by:kamran
ID: 12542077
Hello,
      I am sending my mails through smtp.
      If my mail host is mail.multi.net.pk
      it works well
      If my mail host smtp.dia.sbcglobal.net
      I get error
      javax.mail.MessagingException: 530 5.7.0 Authentication required

my code is

      String host = "smtp.dia.sbcglobal.net";
      String filename = gDesc.getString("email_attachment");
      String msgText1 = "asdasdasd";
      String subject = "email_subject";
      Properties props = System.getProperties();
                props.put("mail.smtp.host", host);
      Session session = Session.getDefaultInstance(props, null);
      session.setDebug(debug);
        try {
          MimeMessage msg = new MimeMessage(session);
          msg.setFrom(new InternetAddress(from));
            InternetAddress[] address = InternetAddress.parse(to);
          msg.setRecipients(Message.RecipientType.TO, address);
          msg.setSubject(subject);

            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(msgText1);
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            msg.setContent(mp);
            msg.setSentDate(new Date());
          Transport.send(msg);
        }
        catch (MessagingException mex)
        {
          mex.printStackTrace();
          Exception ex = null;
          if ((ex = mex.getNextException()) != null)
            {      ex.printStackTrace();          }
       }
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
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…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

708 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now