简体   繁体   English

在JAVA EE 6中发送电子邮件

[英]Sending e-mails in JAVA EE 6

I'm developing a Java EE 6 application deployed on glassfish, I keep reading tutorials about how to send emails but they seem either outdated or too complicated. 我正在开发一个部署在glassfish上的Java EE 6应用程序,我一直在阅读有关如何发送电子邮件的教程,但它们似乎已经过时或过于复杂。 I was hoping that may be in this specification there's a rather simple way to send mail since so many things have become so much simpler. 我希望可能在这个规范中有一种相当简单的发送邮件的方式,因为很多东西变得如此简单。 Can you point me in the right direction or may be show me some sample code? 你能指出我正确的方向还是可以给我看一些示例代码?

You can utilize apache commons email or if you are using Spring then use spring mail . 您可以使用apache commons电子邮件,或者如果您使用Spring,则使用spring邮件 There is always JavaMail if you don't want to use any of the wrapper libraries and a code sample on it. 如果您不想使用任何包装器库和代码示例 ,则始终存在JavaMail

All of these links have code examples. 所有这些链接都有代码示例。

The JEE App Server should provide the email resource. JEE App Server应提供电子邮件资源。 The only think you need to do is lookup the resource (I suppose it is configured) and send the email. 您需要做的唯一考虑是查找资源(我认为它已配置)并发送电子邮件。

//Mail  Resource injection not working on wildfly 10
//@Resource(lookup = "java:/futuramail")
private Session mailSession;

@Asynchronous
@Lock(LockType.READ)
    public void sendMail(String recipient, String subject, String text) {
        try {

            InitialContext ic = new InitialContext();
            mailSession = (Session) ic.lookup("java:/futuramail");
            MimeMessage message = new MimeMessage(mailSession);
            Address[] to = new InternetAddress[]{new InternetAddress(recipient)};
            message.setRecipients(Message.RecipientType.TO, to);
            message.setSubject(subject);
            message.setSentDate(new Date());
            message.setContent(text, "text/html");
            //message.setText(text);
            Transport.send(message);
            System.out.println("mail sent");
        } catch (MessagingException me) {
            me.printStackTrace();
        } catch (NamingException ex) {
            Logger.getLogger(MailProcessor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM