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

对于使用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 {@Autowiredprivate MailSender mailSender;@Autowiredprivate 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.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://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项目。

相关文章 :
  • 依赖注入–手动方式
  • 使用Spring Security保护GWT应用程序
  • 带有Spring和Maven教程的JAX–WS
  • 建立自己的GWT Spring Maven原型
  • 使用Spring AspectJ和Maven进行面向方面的编程
  • Spring3 RESTful Web服务
  • JBoss 4.2.x Spring 3 JPA Hibernate教程

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/374589.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java字符与数字的计算

先看例子&#xff1a; char ch;int x;int y 7;System.out.print("7的ASCII码值是&#xff1a;");System.out.println(y);ch 7 2;System.out.print("7 2的char型&#xff1a;");System.out.println(ch);x 7 2;System.out.print("7 2的int型&…

wordcount

源代码如下 package org.apache.hadoop.examples; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io…

EJB 3.1全局JNDI访问

如本系列前面的部分所述&#xff0c;EJB 3.0版规范的主要缺点是缺少可移植的全局JNDI名称。 这意味着没有可移植的方式将EJB引用链接到应用程序外部的Bean。 EJB v。3.1规范用自己的话填补了这一定义&#xff1a; “一个标准化的全局JNDI名称空间和一系列相关的名称空间&#…

Git 分支管理和冲突解决

创建分支 git branch 没有参数&#xff0c;显示本地版本库中所有的本地分支名称。 当前检出分支的前面会有星号。 git branch newname 在当前检出分支上新建分支&#xff0c;名叫newname。 git checkout newname 检出分支&#xff0c;即切换到名叫newname的分支。 git checkout…

力扣打开转盘锁

打开转盘锁 评论区大神代码&#xff1a; public int openLock(String[] deadends, String target) {Set<String> set new HashSet<>(Arrays.asList(deadends));//开始遍历的字符串是"0000"&#xff0c;相当于根节点String startStr "0000";i…

EJB程序化查找

在上一篇文章中&#xff0c;我们了解了EJB 引用和EJB 注入 。 尽管EJB注入是一种强大的容器工具&#xff0c;可以简化模块化应用程序的开发&#xff0c;但有时还是需要执行程序化EJB查找。 让我们假设&#xff0c;例如&#xff0c;一组不同的EJB实现了由公共业务接口定义的公共…

git克隆/更新/提交代码步骤及示意图

1. git clone ssh://flycm.intel.com/scm/at/atSrc 或者git clone ssh://flycm.intel.com/scm/at/atJar 或者git clone ssh://flycm.intel.com/scm/at/atFramework 2. git checkout cpeg/scm/stable 切换分支&#xff0c;然后更新代码 3. git pull 先把远程分支上最新的代码拉到…

C++面试宝典

1.new、delete、malloc、free关系 delete会调用对象的析构函数,和new对应free只会释放内存&#xff0c;new调用构造函数。malloc与free是C/C语言的标准库函数&#xff0c;new/delete是C的运算符。它们都可用于申请动态内存和释放内存。对于非内部数据类型的对象而言&#xff0c…

Google App Engine:在您自己的域中托管应用程序

在Google App Engine中创建新应用程序时&#xff0c;您将获得一个域名“ yourapp.appspot.com”。 但是&#xff0c;谁会想要以这样的后缀托管他们的应用程序&#xff08;除非您喜欢它&#xff01;&#xff09;&#xff1f; 为了改善您的应用品牌&#xff0c;最好的办法是将您的…

从零开始学 iOS 开发的15条建议

事情困难是事实&#xff0c;再困难的事还是要每天努力去做是更大的事实。 因为我是一路自学过来的&#xff0c;并且公认没什么天赋的前提下&#xff0c;进步得不算太慢&#xff0c;所以有很多打算从零开始的朋友会问我&#xff0c;该怎么学iOS开发。跟粉丝群的朋友交流了一下&a…

垂直居中-父元素高度确定的多行文本(方法二)

除了上一节讲到的插入table标签&#xff0c;可以使父元素高度确定的多行文本垂直居中之外&#xff0c;本节介绍另外一种实现这种效果的方法。但这种方法兼容性比较差&#xff0c;只是提供大家学习参考。 在 chrome、firefox 及 IE8 以上的浏览器下可以设置块级元素的 display 为…

13. 罗马数字转整数

罗马数字转整数 class Solution {public int romanToInt(String s) {Map<Character,Integer> map new HashMap<Character,Integer>(){{put(I,1);put(V,5);put(X,10);put(L,50);put(C,100);put(D,500);put(M,1000);}};int res 0;for(int i 0;i<s.length();i)…

互联网金融P2P主业务场景自动化测试

互联网金融P2P行业&#xff0c;近三年来发展迅速&#xff0c;如火如荼。据不完全统计&#xff0c;全国有3000的企业。“互联网”企业&#xff0c;几乎每天都会碰到一些奇奇怪怪的bug&#xff0c;作为在互联网企业工作的测试人员&#xff0c;风险和压力都巨大。那么我们如何降低…

OSGi将Maven与Equinox结合使用

很长时间以来&#xff0c;我一直在努力理解OSGi的真正含义。 它已经存在很长时间了&#xff0c;但是没有多少人意识到这一点。 人们已经大肆宣传它是一种非常复杂的技术。 这是我为所有Java开发人员简化的尝试。 简而言之&#xff0c; OSGi是一组规范&#xff0c;这些规范允许对…

note05-计算机网络

5.网络安全 被动攻击(UDP报文被截获 被 进行流量分析) 主动攻击 1.篡改(更改报文流 伪报文) 2.恶意程序(病毒、木马、蠕虫、炸弹) 3.拒绝服务Dos 密码体制 1.对称密钥密码体制(DES IDEA) 即加密和解密的密钥K相同 2.公钥密码体制(RSA) A加密使用PKB公钥 B解密使用对应的私钥SK…

825. 适龄的朋友

适龄的朋友 在社交媒体网站上有 n 个用户。给你一个整数数组 ages &#xff0c;其中 ages[i] 是第 i 个用户的年龄。 如果下述任意一个条件为真&#xff0c;那么用户 x 将不会向用户 y&#xff08;x ! y&#xff09;发送好友请求&#xff1a; age[y] < 0.5 * age[x] 7 ag…

struts2设置文件上传大小

利用struts2想要设置或者限制上传文件的大小,可以在struts.xml配置文件里面进行如下配置: <constant name"struts.multipart.maxSize" value"10000000" /> 上面这句话的意思是设置文件上传大小&#xff0c;最大不超过9.8M。计算方式如下&#xff1a;…

Java命名约定

我想写这篇简短的文章来帮助某些难以记住Java API类和方法名称的人。 如您所知&#xff0c;Java是区分大小写的语言&#xff0c;要构建Java程序&#xff0c;您需要使用许多内置API类和方法。 而且&#xff0c;初学者发现很难准确地记住方法名称和类名称而不改变大小写。 但是实…

smarty引擎之练习

关于smarty最直观的感受就是分离了页面中html和php的代码&#xff0c;页面不再混乱&#xff0c;很清晰了…… smarty->assign();//注册 smarty->display();//加载模板 除了老师给的表&#xff0c;kemu,nandu,type都建了表格&#xff0c;便于使用 main.php <?phpinclu…

Heron 论文翻译及理解

Heron 论文翻译及理解 背景介绍&#xff1a; Heron是号称Twitter流数据处理的新一代实现&#xff0c;是StormV2。我们首先回顾一下Storm系统的问题 worker日志混乱&#xff0c;如果一个bolt日志过大&#xff0c;会冲掉其他bolt的日志worker之间因为没有资源隔离&#xff0c;因此…