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("[email protected]"));
		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("[email protected]"));
		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)