从java无状态EJB发送电子邮件(Java EE-6)

sfr*_*frj 4 java glassfish jakarta-mail java-ee ejb-3.0

我想发送一封关于EJB的电子邮件,但我在这个例外中得到的唯一回报是:

java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
Run Code Online (Sandbox Code Playgroud)

这就是我的EJB的样子:

@Stateless(name = "ejbs/EmailServiceEJB")
public class EmailServiceEJB extends Authenticator implements IEmailServiceEJB {

public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("xxxxxxx@gmail.com",
            "xxxxxxx");
}

public void sendAccountActivationLinkToBuyer(String destinationEmail,
        String name) {
    // OUR EMAIL SETTINGS
    String host = "smtp.gmail.com";// Gmail
    int port = 465;
    String serviceUsername = "xxxxxxx@gmail.com";
    String servicePassword = "xxxxxxx";// Our Gmail password

    Properties props = new Properties();
    props.put("mail.smtp.user", serviceUsername);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", port);
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    // Destination of the email
    String to = destinationEmail;
    String from = "xxxxxxx@gmail.com";

    // Creating a javax.Session with the our properties
    Session session = Session.getInstance(props);

    try {
        Message message = new MimeMessage(session);
        // From: is our service
        message.setFrom(new InternetAddress(from));
        // To: destination given
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));
        message.setSubject("Comfirm your account");
        // Instead of simple text, a .html template should be added here!
        message.setText("Welcome....... ");

        Transport transport = session.getTransport("smtp");
        transport.connect(host, port, serviceUsername, servicePassword);
        Transport.send(message, message.getAllRecipients());
        transport.close();

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}
Run Code Online (Sandbox Code Playgroud)

}

我不知道为什么它一直说没有指定密码?SSLSocketFactory与它有关吗?我是否需要在某处调用getPasswordAuthenticion()方法,或者我需要从托管bean调用第二种方法?

Mik*_*zak 9

我不知道为什么你的代码不起作用,但你可能想看看这个:

http://spitballer.blogspot.com/2010/02/sending-email-via-glassfish-v3.html

它显示了在Java EE中配置电子邮件的另一种方法,我认为这种方法效果更好.连接详细信息在容器级别配置,就像容器管理的数据库连接一样.