-
引入jar包
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.3</version> </dependency>
-
创建工具类
import com.sun.mail.util.MailSSLSocketFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.mail.Address; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.text.SimpleDateFormat; import java.util.*; /** * 邮件处理工具类 */ public class MailUtil { private final static Logger logger = LoggerFactory.getLogger(MailUtil.class); public static boolean sendMail(String title, String msgs, Address[] array) { return sendMail(title, msgs, array, false); } public static boolean sendMail(String title, String msgs, Address[] array, boolean isHtml) { try { Properties props = new Properties(); logger.info("发送邮件--start"); // 开启debug调试 props.setProperty("mail.debug", "true"); // 发送服务器需要身份验证 props.setProperty("mail.smtp.auth", "true"); // 设置邮件服务器主机名(我这用的是阿里邮箱) props.setProperty("mail.host", "smtp.qiye.aliyun.com"); // 设置邮件服务器端口 props.setProperty("mail.smtp.port", "465"); // 发送邮件协议名称 props.setProperty("mail.transport.protocol", "smtp"); MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getInstance(props); Message msg = new MimeMessage(session); msg.setSubject(title); StringBuilder builder = new StringBuilder(); builder.append(msgs); builder.append("\n"); builder.append("\n时间 " + formatTime(new Date())); if (isHtml) { msg.setContent(builder.toString(), "text/html;charset = utf-8"); } else { msg.setText(builder.toString()); } // 此处设置发件人邮箱 msg.setFrom(new InternetAddress("abc@ali.com")); Transport transport = session.getTransport(); // (邮件服务器主机名、发件人邮箱、发件人邮箱密码) transport.connect("smtp.qiye.aliyun.com", "support@xidespace.com", "Xide2020"); transport.sendMessage(msg, array); transport.close(); logger.info("发送邮件--end"); return true; } catch (Exception e) { logger.error(e.getMessage(), e); return false; } } public static String formatTime(Date date) { if (date == null) { return ""; } Calendar c1 = Calendar.getInstance(); c1.setTime(new Date()); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return format.format(date); } }
-
调用Test
public static void main(String[] args) { try { String resultMessage = "发送内容啦啦啦啦"; // 添加收件人地址 多个收件人存放list中 List<Address> list = new ArrayList<Address>(); list.add(new InternetAddress("888@163.com")); list.add(new InternetAddress("888@qq.com")); Address[] senderList = list.toArray(new Address[list.size()]); MailUtil.sendMail(formatTime(new Date()) + "测试邮件", resultMessage, senderList); } catch (AddressException e) { logger.error(e.getMessage(), e); } }
java发送邮件通知
最新推荐文章于 2024-09-07 15:57:39 发布