java mail 实现邮件发送功能

由于项目中需要用到发送邮件的功能

项目前后使用了两种实现方式,

一是java mail直接连接邮箱服务器,代码如下




import java.util.Date;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Value;


/**
 * @ClassName: MailSender
 * @Description: TODO(发送邮件)
 * 
 */
public class MailSender {
	    @Value("${emailAccount}")
	    private static String emailAccount;
	    
	    @Value("${emailPassword}")
	    private static String emailPassword;
	    
	    @Value("${emailAddress}")
	    private static String emailAddress;
	    
	    @Value("${emailSMTPHost}")
	    private static String emailSMTPHost;
	    

	    public static void sendMail(MailUser receiver) throws Exception{
	    	
	        // 1. 创建参数配置, 用于连接邮件服务器的参数配置
	        Properties props = new Properties();                    // 参数配置
	        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议(JavaMail规范要求)
	        props.setProperty("mail.smtp.host", ConfigHelper.getProperty("emailSMTPHost"));   // 发件人的邮箱的 SMTP 服务器地址
	        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证
	        
	        // 2. 根据配置创建会话对象, 用于和邮件服务器交互
	        Session session = Session.getInstance(props);
	        session.setDebug(true);                                 // 设置为debug模式, 可以查看详细的发送 log

	        // 3. 创建一封邮件
	        MimeMessage message = createMimeMessage(session, receiver);

	        // 4. 根据 Session 获取邮件传输对象
	        Transport transport = session.getTransport();

	        // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
	        transport.connect(ConfigHelper.getProperty("emailAccount"), ConfigHelper.getProperty("emailPassword"));

	        // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
	        transport.sendMessage(message, message.getAllRecipients());

	        // 7. 关闭连接
	        transport.close();
	    }

	    /**
	     * 创建一封只包含文本的简单邮件
	     *
	     * @param session 和服务器交互的会话
	     * @param sendMail 发件人邮箱
	     * @param receiveMail 收件人邮箱
	     * @return
	     * @throws Exception
	     */
	    public static MimeMessage createMimeMessage(Session session, MailUser receiver) throws Exception {
	        // 1. 创建一封邮件
	        MimeMessage message = new MimeMessage(session);

	        // 2. From: 发件人
	        message.setFrom(new InternetAddress(ConfigHelper.getProperty("emailAddress"), "开发者社区","UTF-8"));

	        // 3. To: 收件人(可以增加多个收件人、抄送、密送)
	        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiver.getEmailAccount(), "UTF-8"));

	        // 4. Subject: 邮件主题
	        message.setSubject(receiver.getSubject(), "UTF-8");

	        // 5. Content: 邮件正文(可以使用html标签)
	        message.setContent(receiver.getContent(), "text/html;charset=UTF-8");

	        // 6. 设置发件时间
	        message.setSentDate(new Date());

	        // 7. 保存设置
	        message.saveChanges();

	        return message;
	    }

}

加载配置的方法如下:项目启动时注入容器中: 



import common.log.Log;
import common.utils.SaveFileOperater;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @ClassName: ConfigHelper
 * @Description: TODO(自定义配制加载类)
 * 
 */
@Configuration
public class ConfigHelper {
	private static final String PROPERTIES_NAME="config.properties";
	private static Properties props;
	static {
		loadProps();
	}

	synchronized static private void loadProps() {
		Log.info("开始加载config properties文件内容.......");
		props = new Properties();
		InputStream in = null;
		try {
			String rootPath = ResourceUtils.getURL("").getPath();
		    String proPath = rootPath+"config"+File.separator+PROPERTIES_NAME;
			Log.info("config properties path......."+proPath);
			File file = SaveFileOperater.generateLegalFile(proPath);
			Resource resource = new FileSystemResource(file);
			if(resource.exists()) {
				in = resource.getInputStream();
			}
			if(in==null) {
				in=ConfigHelper.class.getClassLoader().getResourceAsStream(PROPERTIES_NAME);
			}
			props.load(in);
		} catch (FileNotFoundException e) {
			Log.error("config .properties文件未找到");
		} catch (IOException e) {
			Log.error("出现IOException");
		} finally {
			try {
				if (null != in) {
					in.close();
				}
			} catch (IOException e) {
				Log.error("config .properties文件流关闭出现异常");
			}
		}
		Log.info("加载config properties文件内容完成...........");
		Log.info("config properties文件内容:" + props);
	}

	public static String getProperty(String key) {
		if (null == props) {
			loadProps();
		}
		return props.getProperty(key);
	}

	public static String getProperty(String key, String defaultValue) {
		if (null == props) {
			loadProps();
		}
		return props.getProperty(key, defaultValue);
	}
}

二是调用外部接口,这里暂不赘述,后续更新

package com.lccert.crm.chemistry.util; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMail { private static SendMail instance = null; private SendMail() { } public static SendMail getInstance() { if (instance == null) { instance = new SendMail(); } return instance; } public void send() { try { String to[]={"tiwsonchen@163.com","tiwson@163.com"}; Properties p = new Properties(); //Properties p = System.getProperties(); p.put("mail.smtp.auth", "true"); p.put("mail.transport.protocol", "smtp"); p.put("mail.smtp.host", "smtp.163.com"); p.put("mail.smtp.port", "25"); //建立会话 Session session = Session.getInstance(p); Message msg = new MimeMessage(session); //建立信息 msg.setFrom(new InternetAddress("tiwson@163.com")); //发件人 String toList = getMailList(to); InternetAddress[] iaToList = new InternetAddress().parse(toList); msg.setRecipients(Message.RecipientType.TO,iaToList); //收件人 msg.setSentDate(new Date()); // 发送日期 msg.setSubject("javamail测试邮件"); // 主题 msg.setText("注意,这是测试程序发的,请不要回复!"); //内容 // 邮件服务器进行验证 Transport tran = session.getTransport("smtp"); tran.connect("smtp.163.com", "tiwson", "9041160"); // bluebit_cn是用户名,xiaohao是密码 tran.sendMessage(msg, msg.getAllRecipients()); // 发送 System.out.println("邮件发送成功"); } catch (Exception e) { e.printStackTrace(); } } private String getMailList(String[] mailArray){ StringBuffer toList = new StringBuffer(); int length = mailArray.length; if(mailArray!=null && length <2){ toList.append(mailArray[0]); }else{ for(int i=0;i<length;i++){ toList.append(mailArray[i]); if(i!=(length-1)){ toList.append(","); } } } return toList.toString(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值