使用 Spring 从 Web 应用程序发送邮件

发布于 2024-12-10 13:45:40 字数 69 浏览 0 评论 0原文

在我的网络应用程序中我想发送邮件。有没有办法用 Spring MVC 来做到这一点?最好的方法是什么?

谢谢

In My Web application i want to send mails. Is There any way to do it with Spring MVC ? And what's the best way to do it ?

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蓦然回首 2024-12-17 13:45:41

您可以使用Spring的邮件抽象层轻松发送电子邮件。在 applicationContext.xml 中定义以下 bean

<!-- Mail sender bean -->
<bean id="mailSender" 
        class="org.springframework.mail.javamail.JavaMailSenderImpl">          
<property name="host" value="my.smtp.host" />
<property name="username" value="my_username" />
<property name="password" value="my_password" />
</bean>

<!-- Simple mail template -->
<bean id="basicEmailMessage" 
        class="org.springframework.mail.SimpleMailMessage">
    <property name="from">
        <value>whateverSenderAddress</value>
     </property>
 </bean>

 <!-- Your service with sender and template injected -->
 <bean id="mySendMailService" 
        class="mypackage.MySendMailService">
    <property name="mailSender">
    <ref bean="mailSender" />
    </property>
    <property name="emailTemplate">
        <ref bean="basicEmailMessage" />
    </property>
 </bean>

然后在 mypackage.MySendMailService 中:

public class SendMailService {
    private MailSender mailSender;
    private SimpleMailMessage emailTemplate;
    public void sendEmail(String to, String from, String subject, String body) 
                         throws MailException {
        SimpleMailMessage message = new SimpleMailMessage(this.emailTemplate);
        message.setTo(to);
        message.setFrom(from);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);
    }

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }
    public void setEmailTemplate(SimpleMailMessage emailTemplate) {
        this.emailTemplate = emailTemplate;
    }
}

You can use Spring's mail abstraction layer to easily send emails. Define the following beans in your applicationContext.xml

<!-- Mail sender bean -->
<bean id="mailSender" 
        class="org.springframework.mail.javamail.JavaMailSenderImpl">          
<property name="host" value="my.smtp.host" />
<property name="username" value="my_username" />
<property name="password" value="my_password" />
</bean>

<!-- Simple mail template -->
<bean id="basicEmailMessage" 
        class="org.springframework.mail.SimpleMailMessage">
    <property name="from">
        <value>whateverSenderAddress</value>
     </property>
 </bean>

 <!-- Your service with sender and template injected -->
 <bean id="mySendMailService" 
        class="mypackage.MySendMailService">
    <property name="mailSender">
    <ref bean="mailSender" />
    </property>
    <property name="emailTemplate">
        <ref bean="basicEmailMessage" />
    </property>
 </bean>

Then, in mypackage.MySendMailService:

public class SendMailService {
    private MailSender mailSender;
    private SimpleMailMessage emailTemplate;
    public void sendEmail(String to, String from, String subject, String body) 
                         throws MailException {
        SimpleMailMessage message = new SimpleMailMessage(this.emailTemplate);
        message.setTo(to);
        message.setFrom(from);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);
    }

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }
    public void setEmailTemplate(SimpleMailMessage emailTemplate) {
        this.emailTemplate = emailTemplate;
    }
}
染年凉城似染瑾 2024-12-17 13:45:41

我使用 Apache Velocity 作为电子邮件模板系统。您可以将“VelocityEngine”的实例定义为 spring bean 并将其注入到控制器中。然而,更简洁的解决方案是将邮件发送代码放入服务中,并将服务注入控制器中。

 @Autowired private VelocityEngine velocityEngine;
     @Autowired private JavaMailSender mailSender;

        MimeMessagePreparator preparator = new MimeMessagePreparator() {
                    @Override
                    public void prepare(MimeMessage mimeMessage) throws Exception {
                        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                        message.setTo("[email protected]");
                        message.setFrom("[email protected]");
                        message.setSubject("You got mail!");

                                Map<String, Object> model = new HashMap<String, Object>();
                        model.put("param1", new Date());

                        String text = 
                            VelocityEngineUtils.mergeTemplateIntoString(
                                    velocityEngine, 
                                    "com/myapp/mailtemplates/email.vm", 
                                    model
                            );

                        mimeMessage.setText(text,"utf-8", "html");
                        mimeMessage.setHeader("Content-Type", "text/html; charset=utf-8");
                    }
                };

mailSender.send(preparator);

HashMap 可用于传递参数,然后您可以在速度模板中使用这些参数。
然后您可以使用“JavaMailSender”发送电子邮件,它也可以定义为 spring bean。

您可以像这样定义 mailSender 和velocityEngine bean:

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.mail.com" />
        <property name="username" value="sender" />
        <property name="password" value="password" />
        <property name="javaMailProperties">
            <props>
                <!-- Use SMTP-AUTH to authenticate to SMTP server -->
                <prop key="mail.smtp.auth">true</prop>
                <!-- Use TLS to encrypt communication with SMTP server -->
                <!-- <prop key="mail.smtp.starttls.enable">true</prop> -->
            </props>
        </property>
    </bean>

    <!-- Apache Velocity Email Template Engine -->
    <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="velocityProperties">
            <value>
                resource.loader=class
                class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
            </value>
        </property>
    </bean>

I'm using Apache Velocity as E-Mail templating system. You can define an instance of "VelocityEngine" as a spring bean and inject it into your controllers. The much cleaner solution however is to put the mail-sending code into a service and inject your service into your controller.

 @Autowired private VelocityEngine velocityEngine;
     @Autowired private JavaMailSender mailSender;

        MimeMessagePreparator preparator = new MimeMessagePreparator() {
                    @Override
                    public void prepare(MimeMessage mimeMessage) throws Exception {
                        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                        message.setTo("[email protected]");
                        message.setFrom("[email protected]");
                        message.setSubject("You got mail!");

                                Map<String, Object> model = new HashMap<String, Object>();
                        model.put("param1", new Date());

                        String text = 
                            VelocityEngineUtils.mergeTemplateIntoString(
                                    velocityEngine, 
                                    "com/myapp/mailtemplates/email.vm", 
                                    model
                            );

                        mimeMessage.setText(text,"utf-8", "html");
                        mimeMessage.setHeader("Content-Type", "text/html; charset=utf-8");
                    }
                };

mailSender.send(preparator);

The HashMap can be used to pass parameters you can then use inside your velocity template.
Then you can send your email using a "JavaMailSender" which can also be define as a spring bean.

You can define the mailSender and the velocityEngine beans similar to this:

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.mail.com" />
        <property name="username" value="sender" />
        <property name="password" value="password" />
        <property name="javaMailProperties">
            <props>
                <!-- Use SMTP-AUTH to authenticate to SMTP server -->
                <prop key="mail.smtp.auth">true</prop>
                <!-- Use TLS to encrypt communication with SMTP server -->
                <!-- <prop key="mail.smtp.starttls.enable">true</prop> -->
            </props>
        </property>
    </bean>

    <!-- Apache Velocity Email Template Engine -->
    <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="velocityProperties">
            <value>
                resource.loader=class
                class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
            </value>
        </property>
    </bean>
影子是时光的心 2024-12-17 13:45:41

Spring MVC 是一个 Web框架,它与电子邮件无关。 Spring 框架的另一部分确实支持邮件发送。看看参考文献的第24章指南

Spring MVC is a web framework, and it has nothing to do with email. Another part of the Spring framework does support mail sending though. Take a look at chapter 24 of the ref guide.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文