`
这些年
  • 浏览: 389787 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java 发邮件,短信

    博客分类:
  • java
 
阅读更多

1:简单邮件发送:

    maven包:

<dependency>
<groupId>commons-digester</groupId>
<artifactId>commons-digester</artifactId>   //使用spring.mail发邮件时这个必须有,并且版本不低于它
<version>2.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.6</version>
</dependency>

在网上找到的包:

<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${javamail.version}</version>
</dependency>
</dependencies>
<properties>
<javamail.version>1.4.1</javamail.version>
</properties>

spring的mail包

<dependency>
<groupId>javax.mail</groupId>
<artifactId>com.springsource.javax.mail</artifactId>
<version>1.4.0</version>
</dependency>

 

 java代码:

package com.chinacache.snp.TransferChannelAlarm.util;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class EMailUtil {

	private static String mailServer;
	private static String addresserUser;
	private static String addresserPass;
	private static String cc;
	private static Log logger = LogFactory.getLog(EMailUtil.class);

	public static void init() {
		try {
			PropertiesConfiguration pro = new PropertiesConfiguration("email.properties");
			mailServer = (String) pro.getProperty("email.server");
			addresserUser = (String) pro.getProperty("addresser.user");
			addresserPass = (String) pro.getProperty("addresser.pass");
			cc = pro.getString("cc");
		} catch (ConfigurationException e) {
			logger.error("read email.pro error", e);
		}
	}

	public static void sendMessage(String errorMessage, String addresseeUser) {       //传入邮件内容和收件人(可有多个用,分隔)
		init();
		// 创建环境
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", mailServer);
		props.setProperty("mail.smtp.auth", "true");
		Session session = Session.getInstance(props);
		session.setDebug(true);

		// 创建邮件
		Message message = new MimeMessage(session);

		try {
			setMessage(message, errorMessage, addresseeUser);
			// //发送邮件
			Transport ts = session.getTransport();
			ts.connect(addresserUser, addresserPass);
			ts.sendMessage(message, message.getAllRecipients());
			ts.close();
		} catch (UnsupportedEncodingException e) {
			logger.error("send emai error", e);
		} catch (MessagingException e) {
			logger.error("send emai error", e);
		}

	}

	// 设置邮件
	private static void setMessage(Message message, String errorMessage, String addresseeUser) throws MessagingException,
			UnsupportedEncodingException {
		message.setSubject("转走/测试客户的频道带宽统计表");//主题
		message.setFrom(new InternetAddress("admin@chinacache.com"));
		message.addRecipients(RecipientType.TO,
				InternetAddress.parse(addresseeUser.substring(1, addresseeUser.length() - 1)));//收件人
		message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));//抄送
		MimeBodyPart text = new MimeBodyPart();
		text.setContent(errorMessage, "text/html;charset=utf-8");

		MimeMultipart part = new MimeMultipart("mixed");
		part.addBodyPart(text);

		message.setContent(part);
		message.saveChanges();

	}
}

  email.properties文件内容:

email.server=
addresser.user=
addresser.pass=
cc=

 2:邮件中有附件

package com.chinacache.snp.bill.datacontrast.util;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;

public class EmailUtil {
	private static String mailServer;
	private static String addresserUser;
	private static String addresserPass;
	private static String addresseeUser;
	private static Logger logger = Logger.getLogger(EmailUtil.class);

	private static void init() {
		try {
			PropertiesConfiguration pro = new PropertiesConfiguration("email.properties");
			mailServer = (String) pro.getProperty("email.server");
			addresserUser = (String) pro.getProperty("addresser.user");
			addresserPass = (String) pro.getProperty("addresser.pass");
			addresseeUser = (String) pro.getList("addressee.user").toString();
		} catch (ConfigurationException e) {
			logger.error("read email.pro error", e);
		}
	}

	public static void sendMessage(String errorMessage, List<String> files) {
		init();
		// 创建环境
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", mailServer);
		props.setProperty("mail.smtp.auth", "true");
		Session session = Session.getInstance(props);
		session.setDebug(true);

		// 创建邮件
		Message message = new MimeMessage(session);

		try {
			setMessage(message, errorMessage, files);
			// //发送邮件
			Transport ts = session.getTransport();
			ts.connect(addresserUser, addresserPass);
			ts.sendMessage(message, message.getAllRecipients());
			ts.close();
		} catch (UnsupportedEncodingException e) {
			logger.error("send emai error", e);
		} catch (MessagingException e) {
			logger.error("send emai error", e);
		}

	}

	// 设置邮件
	private static void setMessage(Message message, String errorMessage, List<String> files) throws MessagingException,
			UnsupportedEncodingException {
		message.setSubject("主备系统数据对比结果");
		message.setFrom(new InternetAddress("BillDataContrast@chinacache.com"));
		message.addRecipients(RecipientType.TO,
				InternetAddress.parse(addresseeUser.substring(1, addresseeUser.length() - 1)));

		MimeBodyPart text = new MimeBodyPart();
		text.setContent(errorMessage, "text/html;charset=utf-8");

		MimeMultipart part = new MimeMultipart("mixed");
		part.addBodyPart(text);

		if (files!=null&&!files.isEmpty()) {// 有附件
			for (String filename : files) {
				text = new MimeBodyPart();
				FileDataSource fds = new FileDataSource(filename); // 得到数据源
				text.setDataHandler(new DataHandler(fds)); // 得到附件本身并至入BodyPart
				text.setFileName(fds.getName()); // 得到文件名同样至入BodyPart
				part.addBodyPart(text);
			}
			files.clear();
		}

		message.setContent(part);
		message.saveChanges();
	}
}

 email.properties文件内容

email.server=
addresser.user=
addresser.pass=
addressee.user=

 3:发信息

package com.chinacache.bee.service.alarm;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class ShortMessageService {

    private Logger logger = Logger.getLogger(ShortMessageService.class);
    private String smsServerUrl;
    private String userName;
    private String password;
    private String smsContent = null;

    public String getSmsContent() {
        return smsContent;
    }

    public void setSmsContent(String smsContent) {
        this.smsContent = smsContent;
    }

    public boolean sendSMS(String[] mobiles, Map<Object, Object> parameterMap) throws Exception {
        if (mobiles == null || mobiles.length < 1) {
            logger.error("There is no mobile to send to.");
            return true;
        }
        return sendSMS(mobiles, smsContent);
    }

    public boolean sendSMS(String[] mobiles, String content) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("SMS Server URL [ " + smsServerUrl + " ]");
            logger.debug("SMS receive mobiles [ " + Arrays.toString(mobiles) + " ]");
            logger.debug("SMS content [ " + content + " ]");
        }

        boolean sendResult = false;
        DefaultHttpClient httpclient = new DefaultHttpClient();

        // 设置短信服务器地址
        HttpPost httpost = new HttpPost(smsServerUrl);

        // 设置短信服务的账号信息
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", userName));
        nvps.add(new BasicNameValuePair("password", password));
        nvps.add(new BasicNameValuePair("mobile", StringUtils.join(mobiles, ";")));// 将多个手机号转换为以分好分隔的字符串
        nvps.add(new BasicNameValuePair("content", content));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String responseContent = EntityUtils.toString(entity);

            if ("0".equals(responseContent.split("\\s")[0].trim())) {// 如果返回0则表明发送成功
                sendResult = true;
            }
            if (logger.isDebugEnabled()) {
                logger.debug("SMS server response string [ " + responseContent + " ]");
            }
        }
        httpclient.getConnectionManager().shutdown();
        return sendResult;
    }

    public String getSmsServerUrl() {
        return smsServerUrl;
    }

    public void setSmsServerUrl(String smsServerUrl) {
        this.smsServerUrl = smsServerUrl;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

 xml中的bean配置(用到了spring)

写道
<bean id="shortMessageService" class="com.chinacache.bee.service.alarm.ShortMessageService">
<property name="smsServerUrl" value="http://sms.chinacache.com/ReceiverSms" />
<property name="userName" value="" />
<property name="password" value="" />
</bean>

 

分享到:
评论

相关推荐

    Java毕业设计-基于Springboot+Vue旅游网站设计-源码+数据库+使用文档+演示视频(高分项目).zip

    Java毕业设计-基于Springboot+Vue旅游网站设计-源码+数据库+使用文档+演示视频(高分项目).zip本资源中的源码都是经过本地编译过可运行的,评审分达到95分以上。资源项目的难度比较适中,内容都是经过助教老师审定过的能够满足学习、使用需求,如果有需要的话可以放心下载使用。 Java毕业设计-基于Springboot+Vue旅游网站设计-源码+数据库+使用文档+演示视频(高分项目).zipJava毕业设计-基于Springboot+Vue旅游网站设计-源码+数据库+使用文档+演示视频(高分项目).zipJava毕业设计-基于Springboot+Vue旅游网站设计-源码+数据库+使用文档+演示视频(高分项目).zipJava毕业设计-基于Springboot+Vue旅游网站设计-源码+数据库+使用文档+演示视频(高分项目).zipJava毕业设计-基于Springboot+Vue旅游网站设计-源码+数据库+使用文档+演示视频(高分项目).zipJava毕业设计-基于Springboot+Vue旅游网站设计-源码+数据库+使用文档+演示视频(高分项目).zip

    Music-app-master.zip

    Music-app-master

    基于springboot的权限管理系统.zip

    基于springboot的java毕业&课程设计

    外东洪路中段.m4a

    外东洪路中段.m4a

    基于matlab+Simulink模拟的微电网系统包括包括电源、电力电子设备等+源码+开发文档(毕业设计&课程设计&项目开发)

    基于matlab+Simulink模拟的微电网系统包括包括电源、电力电子设备等+源码+开发文档,适合毕业设计、课程设计、项目开发。项目源码已经过严格测试,可以放心参考并在此基础上延申使用~ 项目简介: 这是一个完整的微电网模型,包括电源、电力电子设备、使用MatLab和Simulink的负载和电源模型。该模型基于费萨尔·穆罕默德的硕士论文《微网格建模与仿真》。 什么是微电网 模拟的微电网使用一组电源和负载在与任何集中式电网(宏电网)断开连接的情况下工作,并自主运行,为其局部区域提供电力。该仿真对微电网在稳态下进行建模,以分析其对输入变化的瞬态响应。 此模拟的目的 对系统进行全年模拟,测量负载、产量、电压和频率。 给出简化规划和资源评估阶段的方法。

    MySQL8.4.0 LTS(mysql-server-8.4.0-1debian12-amd64.deb-bundle)

    MySQL8.4.0 LTS(mysql-server_8.4.0-1debian12_amd64.deb-bundle.tar)适用于Debian 12 Linux (x86, 64-bit)

    改进混沌游戏优化(ICgo)matlab代码.zip

    1.版本:matlab2014/2019a/2021a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    基于SpringBoot,SpringCloud的微服务大型在线学习平台实现.zip

    基于springboot的java毕业&课程设计

    圣经投屏软件(5种语言版本)

    圣经投屏软件(5种语言版本)

    基于SpringBoot,Spring Security实现的前后端分离权限管理简易系统.zip

    基于springboot的java毕业&课程设计

    jSP在线教学质量评价系统的设计与实现(源代码)

    在线教学质量评价系统可以方便和全面地收集教师教学工作的数据,提供师生网上评教的评分结果,快速集中收集各方面的评教信息,使教务管理部门能够及时了解教学动态和师资情况,为教务老师提供相关决策支持,为职称评聘提供教学工作质量的科学依据,同时减轻了教务老师的工作量。

    测障测角小车程序+仿真电路DSN文件+设计报告doc.zip

    包含作品的设计论文doc文档+测障测角小车程序+仿真电路DSN文件,可直接修改,适合于电赛备赛、课程设计、毕设参考等。 设计制作了一款具有智能判断功能的小车,功能强大。小车具有以下几个功能:自动避障功能;寻迹功能(按路面的黑色轨道行驶);趋光功能(寻找前方的点光源并行驶到位);检测路面所放置的铁片的个数的功能;计算并显示所走的路程和行走的时间,并可发声发光。作品可以作为大学生学习嵌入式控制的强有力的应用实例。     作品以两电动机为主驱动,通过各类传感器件来采集各类信息,送入主控单元AT89S52单片机,处理数据后完成相应动作,以达到自身控制。电机驱动电路采用高电压,高电流,四通道驱动集成芯片L293D。其中避障采用红外线收发来完成;铁片检测部分采用电感式接近开关LJ18A3-8-Z/BX检测;黑带检测采用红外线接收二极管完成;趋光部分通过3路光敏二极管对光源信号的采集,再经过ADC0809转化为数字信号送单片机处理判别方向。由控制单元处理数据后完成相应动作,实现了无人控制即可完成一系列动作,相当于简易机器人。 关键字:智能控制   蔽障  红外线收发  寻迹行驶  趋光行驶

    基于Python卷积神经网络人脸识别驾驶员疲劳检测与预警系统设计

    1412基于Python卷积神经网络人脸识别驾驶员疲劳检测与预警系统设计毕业源码案例设计 卷积神经网络(Convolutional Neural Networks, CNNs 或 ConvNets)是一类深度神经网络,特别擅长处理图像相关的机器学习和深度学习任务。它们的名称来源于网络中使用了一种叫做卷积的数学运算。以下是卷积神经网络的一些关键组件和特性: 卷积层(Convolutional Layer): 卷积层是CNN的核心组件。它们通过一组可学习的滤波器(或称为卷积核、卷积器)在输入图像(或上一层的输出特征图)上滑动来工作。 滤波器和图像之间的卷积操作生成输出特征图,该特征图反映了滤波器所捕捉的局部图像特性(如边缘、角点等)。 通过使用多个滤波器,卷积层可以提取输入图像中的多种特征。 激活函数(Activation Function): 在卷积操作之后,通常会应用一个激活函数(如ReLU、Sigmoid或tanh)来增加网络的非线性。 池化层(Pooling Layer): 池化层通常位于卷积层之后,用于降低特征图的维度(空间尺寸),减少计算量和参数数量,同时保持特征的空间层次结构。 常见的池化操作包括最大池化(Max Pooling)和平均池化(Average Pooling)。 全连接层(Fully Connected Layer): 在CNN的末端,通常会有几层全连接层(也称为密集层或线性层)。这些层中的每个神经元都与前一层的所有神经元连接。 全连接层通常用于对提取的特征进行分类或回归。 训练过程: CNN的训练过程与其他深度学习模型类似,通过反向传播算法和梯度下降(或其变种)来优化网络参数(如滤波器权重和偏置)。 训练数据通常被分为多个批次(mini-batches),并在每个批次上迭代更新网络参数。 应用: CNN在计算机视觉领域有着广泛的应用,包括图像分类、目标检测、图像分割、人脸识别等。 它们也已被扩展到处理其他类型的数据,如文本(通过卷积一维序列)和音频(通过卷积时间序列)。 随着深度学习技术的发展,卷积神经网络的结构和设计也在不断演变,出现了许多新的变体和改进,如残差网络(ResNet)、深度卷积生成对抗网络(DCGAN)等。

    基于Vue + SpringBoot实现的前后端分离的仿小米商城项目.zip

    基于springboot的java毕业&课程设计

    QKD 协议密钥率的数值评估matlab代码.zip

    1.版本:matlab2014/2019a/2021a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    基于springboot校园社团管理.zip

    基于springboot的java毕业&课程设计

    基于卷积神经网络的城市感知评估.zip

    卷积神经网络(Convolutional Neural Networks, CNNs 或 ConvNets)是一类深度神经网络,特别擅长处理图像相关的机器学习和深度学习任务。它们的名称来源于网络中使用了一种叫做卷积的数学运算。以下是卷积神经网络的一些关键组件和特性: 卷积层(Convolutional Layer): 卷积层是CNN的核心组件。它们通过一组可学习的滤波器(或称为卷积核、卷积器)在输入图像(或上一层的输出特征图)上滑动来工作。 滤波器和图像之间的卷积操作生成输出特征图,该特征图反映了滤波器所捕捉的局部图像特性(如边缘、角点等)。 通过使用多个滤波器,卷积层可以提取输入图像中的多种特征。 激活函数(Activation Function): 在卷积操作之后,通常会应用一个激活函数(如ReLU、Sigmoid或tanh)来增加网络的非线性。 池化层(Pooling Layer): 池化层通常位于卷积层之后,用于降低特征图的维度(空间尺寸),减少计算量和参数数量,同时保持特征的空间层次结构。 常见的池化操作包括最大池化(Max Pooling)和平均池化(Average Po

    课设毕设基于SpringBoot+Vue的医院急诊系统 LW+PPT+源码可运行.zip

    课设毕设基于SpringBoot+Vue的医院急诊系统 LW+PPT+源码可运行.zip

    无人驾驶实战-无人驾驶高精地图

    无人驾驶高精地图,学习无人驾驶高精地图

    企业数据治理之数据存储治理方案.pptx

    企业数据治理之数据存储治理方案

Global site tag (gtag.js) - Google Analytics