使用Spring使用Java发送电子邮件– GMail SMTP服务器示例

本文介绍如何在Java应用中使用Spring框架的邮件服务发送电子邮件,特别是通过GMail SMTP服务器。文章讨论了所需的JavaMail API和Spring库,以及如何配置Spring XML文件以设置SMTP服务器属性和凭据。此外,还展示了如何创建一个简单的邮件服务类,用于发送预配置和自定义的邮件。
摘要由CSDN通过智能技术生成

对于使用Java发送电子邮件, JavaMail API是标准解决方案。 如官方网页所述,“ JavaMail API提供了独立于平台和协议的框架来构建邮件和消息传递应用程序”。 必需的类包含在JavaEE平台中,但是要在独立的JavaSE应用程序中使用它,您必须从这里下载相应的JAR。

注意:除非您使用Java SE 6,否则还需要提供javax.activation包的JavaBeans激活框架(JAF)扩展。 我们建议您使用最新版本的JAF 1.1.1版本。 JAF包含在Java SE 6中。

不幸的是,JavaMail可能有点笨拙,并且难以配置和使用。 如果您已经为应用程序拥抱了Spring框架 ,那么您将很高兴发现Spring提供了一个邮件抽象层。 如参考文档所述,“ Spring框架提供了一个有用的实用程序库,用于发送电子邮件,该电子邮件使用户免受底层邮件系统的限制,并负责代表客户端进行低级资源处理。” 太好了,现在让我们看看如何利用这个库。

首先,创建一个名为“ SpringMailProject”的新Eclipse项目。 在项目的类路径中,确保包括以下库(请注意,使用的是3.0.2.RELEASE Spring版本):

  • mail.jar(JavaMail的核心类)
  • org.springframework.asm-3.0.2.RELEASE.jar
  • org.springframework.beans-3.0.2.RELEASE.jar
  • org.springframework.context.support-3.0.2.RELEASE.jar
  • org.springframework.core-3.0.2.RELEASE.jar
  • org.springframework.expression-3.0.2.RELEASE.jar
  • com.springsource.org.apache.commons.logging-1.1.1.jar

注意1:需要Apache的commons-logging库,该库包含在classpath中
注意2:如果您使用的是Java 1.5或更早版本,则还需要Java激活框架。

我们将使用MailSender ,这是一个Spring接口,用于定义发送简单邮件的策略。 由于这只是一个接口,因此我们需要一个具体的实现,并以JavaMailSenderImpl的形式出现。 此类同时支持JavaMail MimeMessage和Spring SimpleMailMessage

我们将创建一个简单的Spring服务,该服务将用于发送邮件。 一种方法将在现场创建SimpleMailMessage ,而另一种方法将使用预配置的默认消息。 该服务的源代码如下:

package com.javacodegeeks.spring.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

@Service("mailService")
public class MailService {
    
    @Autowired
    private MailSender mailSender;
    @Autowired
    private SimpleMailMessage alertMailMessage;
    
    public void sendMail(String from, String to, String subject, String body) {
        
        SimpleMailMessage message = new SimpleMailMessage();
         
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);
        
    }
    
    public void sendAlertMail(String alert) {
        
        SimpleMailMessage mailMessage = new SimpleMailMessage(alertMailMessage);
        mailMessage.setText(alert);
        mailSender.send(mailMessage);
        
    }
    
}

该类只是一个POJO,其服务名称为“ mailService”,由构造型Service批注标记。 使用的bean接线策略是自动装配之一 ,因此使用了Autowired注释。 注意,可以使用bean的名称和类型来执行自动装配。

引导容器的相应Spring XML文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
>

    <context:component-scan base-package="com.javacodegeeks.spring.mail" />    
    
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com"/>
        <property name="port" value="25"/>
        <property name="username" value="myusername@gmail.com"/>
        <property name="password" value="mypassword"/>
        <property name="javaMailProperties">
            <props>
                <!-- Use SMTP transport protocol -->
                <prop key="mail.transport.protocol">smtp</prop>
                <!-- 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>
                <prop key="mail.debug">true</prop>
            </props>
        </property>
    </bean>
    
    <bean id="alertMailMessage" class="org.springframework.mail.SimpleMailMessage">
        <property name="from">            
            <value>myusername@gmail.com</value>
        </property>
        <property name="to">            
            <value>myusername@gmail.com</value>
        </property>
        <property name="subject" value="Alert - Exception occurred. Please investigate"/>
    </bean>
    
</beans>

这是一个非常简单的Spring配置文件。 不过,有些事情要提及:

  • 声明从其开始上下文扫描的基本软件包,并将其设置为“ com.javacodegeeks.spring.mail”。
  • 声明了“ mailSender” bean,并适当设置了其一堆属性(使用您自己的SMTP服务器配置属性和凭据)。
  • “ alertMailMessage”是预配置的Spring SimpleMailMessage,将使用“按名称自动装配”将其注入“ MailService”类中。

如果您希望使用Gmail的SMTP服务器,请确保正确配置了以下JavaMail属性:

host=smtp.gmail.com
port=25
username=your-gmail-username
password=your-gmail-password
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.starttls.enable=true

在开发阶段,如果希望邮件客户端生成信息性日志,请将“ mail.debug”设置为true。 但是,请记住在生产时将其设置为false,因为日志量可能会降低应用程序的性能和/或填充硬盘。

最后,我们创建一个类,该类将用于创建Spring容器并测试我们创建的简单邮件服务。 源代码如下:

package com.javacodegeeks.spring.mail;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class MailServiceTest {

    public static void main(String[] args) {
        
        ApplicationContext context = new FileSystemXmlApplicationContext("conf/spring.xml");

        MailService mailService = (MailService) context.getBean("mailService");
        
        mailService.sendMail("myusername@gmail.com", "myusername@gmail.com", "Testing123", "Testing only \n\n Hello Spring Email Sender");
        
        mailService.sendAlertMail("Exception occurred");
        
    }
    
}

FileSystemXmlApplicationContext类用作ApplicationContext 。 我们在构造函数中传递Spring的XML文件位置,该类创建容器,实例化Bean并处理依赖项。 你不爱春天吗? 接下来,我们使用“ getBean ”方法检索“ MailService”服务的引用,并调用这两个方法。

就这样。 与往常一样,您可以从此处下载完整的Eclipse项目。

相关文章 :

翻译自: https://www.javacodegeeks.com/2010/07/java-mail-spring-gmail-smtp.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值