开发者

Sending e-mails in JAVA EE 6

开发者 https://www.devze.com 2023-02-08 00:27 出处:网络
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. I was hoping that may be in this spec

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. I was hoping that may be in this specific开发者_开发技巧ation 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. There is always JavaMail if you don't want to use any of the wrapper libraries and a code sample on it.

All of these links have code examples.


The JEE App Server should provide the email resource. 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);
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消