?
Solved

JavaMail SMTP Send Mail : MAIL requires AUTH

Posted on 2004-09-16
18
Medium Priority
?
32,504 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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
 

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 500 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
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…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This video teaches viewers about errors in exception handling.
Suggested Courses

718 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