• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 32577
  • Last Modified:

JavaMail SMTP Send Mail : MAIL requires AUTH

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
eddie81
Asked:
eddie81
  • 4
  • 3
  • 3
  • +2
1 Solution
 
TimYatesCommented:
what happens if you try to connect straight to

   mail1.host.com

instead of

    smtp1.host.com

?
0
 
TimYatesCommented:
I guess you may get relay errors then :-(
0
 
CEHJCommented:
>>  _mailSession = Session.getDefaultInstance(p, null);

You're passing null - you should be passing an Authenticator instance
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
CEHJCommented:
_mailSession = Session.getDefaultInstance(p, new Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
            return PasswordAuthentication("username", "password");
      }
});
0
 
achilkaCommented:
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
 
eddie81Author Commented:
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
 
TimYatesCommented:
_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
 
eddie81Author Commented:
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
 
eddie81Author Commented:
How can I send email using SMTP protocal with SSL via Javamail?

Any source code will be appreciated.
Eddie
0
 
CEHJCommented:
It's probably got a bit easier than this since this was written, but:

http://www.javaworld.com/javatips/jw-javatip115.html
0
 
achilkaCommented:
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
 
achilkaCommented:
Merge the above piece of code into you servlet ...it should work...if it doesn't then check your username and password...Cheers!!!
0
 
CEHJCommented:
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
 
kamranCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

  • 4
  • 3
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now