jboss - 配置jboss发送电子邮件

标签 jboss smtp jakarta-mail

我想从 jboss 中的 servlet 发送电子邮件。我已经在 jboss mail-service.xml 文件中进行了更改。这是我的 servlet 代码。

import java.io.*;
import java.net.*;

import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.*;
import javax.servlet.http.*;

public class Email extends HttpServlet {

    protected void processRequest(HttpServletRequest request, 
                                  HttpServletResponse response)
                   throws IOException, ServletException {

        final String err = "/error.jsp";
        final String succ = "/success.jsp";

        String from = "*******@gmail.com";
        String to = "*******@yahoo.in";
        String subject = "from servlet";
        String message = "HI";
        String login = "***@gmail.com";
        String password = "*******";

        try {
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");

            Authenticator auth = new SMTPAuthenticator(login, password);

            Session session = Session.getInstance(props, auth);

            MimeMessage msg = new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);

        } catch (AuthenticationFailedException ex) {
            /*request.setAttribute("ErrorMessage", "Authentication failed");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);*/
            System.out.println("Authentication failed");

        } catch (AddressException ex) {
            /*request.setAttribute("ErrorMessage", "Wrong email address");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);*/
            System.out.println("Wrong Email Address");

        } catch (MessagingException ex) {
            /*request.setAttribute("ErrorMessage", ex.getMessage());

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);*/
            System.out.println("asdsad"+ex.getMessage());
        }
            /*RequestDispatcher dispatcher = request.getRequestDispatcher(succ);
            dispatcher.forward(request, response);*/
             System.out.println("Success");
    }

    private class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }
}

这是我的 mail-service.xml 文件。

mbean code="org.jboss.mail.MailService" name="jboss:service=Mail">
<attribute name="JNDIName">java:/Mail</attribute>
<attribute name="User">*****@gmail.com</attribute>
<attribute name="Password">******</attribute>
<attribute name="Configuration">
  <!-- A test configuration -->
  <configuration>
    <!-- Change to your mail server prototocol -->
    <property name="mail.store.protocol" value="pop3" />
    <property name="mail.transport.protocol" value="smtp" />

    <!-- Change to the user who will receive mail  -->
    <property name="mail.user" value="nobody" />

    <!-- Change to the mail server  -->
    <property name="mail.pop3.host" value="pop.gmail.com" />

    <!-- Change to the SMTP gateway server -->
    <property name="mail.smtp.host" value="smtp.gmail.com" />
    <property name="mail.smtp.auth" value="true" />
    <property name="mail.smtp.user" value="******@gmail.com" />
    <property name="mail.smtp.password" value="******" />
    <property name="mail.smtp.ssl.enable" value="true" />
    <property name="mail.smtp.starttls.enable" value="true" />
    <property name="mail.smtp.socketFactory.class" 
                 value="javax.net.ssl.SSLSocketFactory" />

    <!-- The mail server port -->
    <property name="mail.smtp.port" value="465" />

    <!-- Change the default address mail will be from  -->
    <property name="mail.from" value="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f697859e819f98949e859d84b6919b979f9ad895999b" rel="noreferrer noopener nofollow">[email protected]</a>" />

    <!-- Enable debugging output from the javamail classes -->
    <property name="mail.debug" value="false" />
  </configuration>
</attribute>
<depends>jboss:service=Naming</depends>

但是在运行时我收到以下异常和根本原因。

    type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Error instantiating servlet class Email
    org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)
    org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:153)
    org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
    org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
    java.lang.Thread.run(Thread.java:722)

root cause

java.lang.NoClassDefFoundError: Email$SMTPAuthenticator
    java.lang.Class.getDeclaredConstructors0(Native Method)
    java.lang.Class.privateGetDeclaredConstructors(Class.java:2404)
    java.lang.Class.getConstructor0(Class.java:2714)
    java.lang.Class.newInstance0(Class.java:343)
    java.lang.Class.newInstance(Class.java:325)
    org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)
    org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:153)
    org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
    org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
    java.lang.Thread.run(Thread.java:722)

note The full stack trace of the root cause is available in the Apache Tomcat/5.5.9 logs.
Apache Tomcat/5.5.9

我哪里出错了?

最佳答案

mailservice.xml 中没有任何更改。在您的 servlet 的 doPost 方法中,删除其他所有内容并粘贴此内容。我希望它对你有用。

 String host = "smtp.gmail.com";
        String from = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfaaacbaad9fb8b2beb6b3f1bcb0b2" rel="noreferrer noopener nofollow">[email protected]</a>";
        String pass = "*******";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        String[] to = {"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="13666061536a727b7c7c3d7a7d" rel="noreferrer noopener nofollow">[email protected]</a>"}; // added this line

        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i=0; i < to.length; i++ ) { // changed from a while loop
            toAddress[i] = new InternetAddress(to[i]);
        }
        System.out.println(Message.RecipientType.TO);

        for( int i=0; i < toAddress.length; i++) { // changed from a while loop
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }
        message.setSubject("sending in a group");
        message.setText("Welcome to JavaMail");
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

关于jboss - 配置jboss发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9407567/

相关文章:

java - slf4j + log4j2 不写入文件

grails - 性能问题碧 Jade 报告和grails/groovy

spring - 尝试在我的 WAR 中运行 Spring @Transactional 服务方法时出现 "transaction is not active"

Django SMTP 身份验证最佳实践

java - 使用 SendGrid 和 Spring 发送邮件

Javax.mail - 无法从正文部分类型获取不同的值

javax.mail.Session构造函数 "is not visible"

java - 从 Tomcat 6 访问 JBoss AS 7.x 中的 EJB 时出现问题

php - 发送电子邮件时更改 HELO 主机名

打开邮箱、读取现有邮件和启动 MessageCountListener 时的 Javamail 同步