如何通过servlet发送邮件?

时间:2014-04-04 09:58:18

标签: java email servlets

我能够通过java中的独立应用程序发送邮件。但是每当我在servlet中嵌入相同的代码时,我都会遇到“无法连接到smtp.gmail.com端口587”的异常。 但是当我使用独立应用程序而不是servlet时,相同的代码工作得很好。我正在使用Mozilla firefox浏览器进行servlet。

1 个答案:

答案 0 :(得分:0)

我想说的是这样的例子:

制作身份验证员:

public class SMTPAuthenticator {

    public Session getSession() throws FileNotFoundException, IOException {
        Authenticator authenticator = new Authenticator();
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true");
        properties.setProperty("mail.smtp.host", "smtp.gmail.com");
        properties.setProperty("mail.smtp.port", "587");

        return Session.getInstance(properties, authenticator);
    }

    private class Authenticator extends javax.mail.Authenticator {

        private final PasswordAuthentication authentication;

        public Authenticator() throws FileNotFoundException, IOException {
            authentication = new PasswordAuthentication("username", "password");
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }
}

然后在其他一些类中使用void方法:

public void sendemail() {

        SMTPAuthenticator sm = new SMTPAuthenticator();
        String username = "fromemailaddress@gmail.com";


        try {

            System.out.println("Sending ......");
            Message message = new MimeMessage(sm.getSession());
            message.setFrom(new InternetAddress(username));
            message.setRecipient(Message.RecipientType.CC, new InternetAddress("toemailaddress@host.com"));
            message.setSubject(subject);
            message.setContent(mess, "text/plain");
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(mess);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            Transport.send(message);
    }

现在最后在你的Servlet Post方法中:

@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    YourClass myclass = new YourClass();
    myclass.sendEmail();//Call the above send method.

    }