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);
	}
}

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

你可能感兴趣的:(java,mail,java后端)