首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Struts2 整合 JavaMail 實現郵件發送功能完整教程

     編輯:Java 相關知識

專案依賴

  • mail.jar (JavaMail API 1.4.4+)
  • activation.jar (JDK 1.6+ 已內置,舊版需引入)
  • 放入 WEB-INF/lib。

1. Action 類封裝發送邏輯

public class Emailer extends ActionSupport {
    private String from, password, to, subject, body;
    // getter/setter 省略

    static Properties props = new Properties();
    static {
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
    }

    public String execute() {
        try {
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, password);
                }
            });
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            msg.setSubject(subject);
            msg.setText(body);
            Transport.send(msg);
            return SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
    }
}

2. 視圖層

index.jsp - 郵件表單

<form action="emailer" method="post">
    From: <input name="from"/><br/>
    Password: <input type="password" name="password"/><br/>
    To: <input name="to"/><br/>
    Subject: <input name="subject"/><br/>
    Body: <input name="body"/><br/>
    <input type="submit" value="Send Email"/>
</form>

success.jsp / error.jsp

<!-- success -->Your email to <s:property value="to"/> was sent successfully.
<!-- error -->There is a problem sending your email to <s:property value="to"/>.

3. Struts 配置

<action name="emailer" class="com.yiibai.struts2.Emailer" method="execute">
    <result name="success">/success.jsp</result>
    <result name="error">/error.jsp</result>
</action>

4. SSH 整合進階:Spring 管理 JavaMail

applicationContext.xml

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com"/>
    <property name="username" value="your@gmail.com"/>
    <property name="password" value="yourpass"/>
    <property name="port" value="465"/>
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
            <prop key="mail.smtp.auth">true</prop>
        </props>
    </property>
</bean>

<bean id="sendMailAction" class="cn.com.action.SendMailAction" singleton="false">
    <property name="mailSender" ref="mailSender"/>
</bean>

Action 中使用 Spring MailSender

public class SendMailAction extends ActionSupport {
    private JavaMailSenderImpl mailSender;
    public void setMailSender(JavaMailSenderImpl mailSender) { this.mailSender = mailSender; }

    public void sendMail() {
        // 1. 簡單郵件
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom("webadmin@163.com");
        msg.setTo("user@163.com");
        msg.setSubject("測試");
        msg.setText("內容");
        mailSender.send(msg);

        // 2. HTML 郵件
        MimeMessage mime = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mime, true, "UTF-8");
        helper.setFrom("webadmin@163.com");
        helper.setTo("user@163.com");
        helper.setSubject("HTML 郵件");
        helper.setText("<h1>Hello</h1>", true); // true=HTML
        mailSender.send(mime);

        // 3. 內嵌圖片
        helper.setText("<img src='cid:logo'>", true);
        FileSystemResource img = new FileSystemResource(new File("c:/logo.jpg"));
        helper.addInline("logo", img);
        mailSender.send(mime);
    }
}

5. 關鍵點總結

  • Struts2 Action 接收表單參數,調用 JavaMail 發送。
  • 生產環境建議:密碼加密存儲、異步發送(線程池/消息隊列)、詳細異常處理與重試。
  • Spring 整合簡化配置,JavaMailSenderImpl 統一管理連接參數,Action 僅關注業務組裝。
  • 複雜郵件(附件、內嵌圖片、HTML)使用 MimeMessageHelper 更便捷。

總結

通過 Struts2 + JavaMail(或 Spring Mail)可快速構建 Web 郵件發送功能,掌握核心 API 與整合模式,滿足註冊驗證、通知推營等常見場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved