maven引用 <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
工具类: package com.xxx.seller.invoice.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.mail.Message; import javax.mail.MessagingException; 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.util.Properties; /** * 只提供报警使用 !!!!! * 业务发送邮件不可用!!!!! */ public class EmailUtils { private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class); private static String[] emails = {"123@xxx.com","456@xx.com"}; /** * 只提供报警使用 !!!!! * 业务发送邮件不可用!!!!! */ public static void sendEmail(String subject,String content){ // 收件人电子邮箱 Properties props = new Properties(); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.transport.protocol", "smtp"); props.put("mail.smtp.host","smtp.163.com");// smtp服务器地址 Session session = Session.getInstance(props); session.setDebug(false); Message msg = new MimeMessage(session); try { msg.setSubject(subject); msg.setText(content); //发件人邮箱 msg.setFrom(new InternetAddress("xxx@163.com")); //收件人邮箱,可设置list if (emails.length>0){ InternetAddress[] ts = new InternetAddress[emails.length]; for (int i = 0; i < emails.length; i++) { String email = emails[i]; InternetAddress internetAddress = new InternetAddress(email); ts[i]=internetAddress; } msg.addRecipients(Message.RecipientType.TO,ts); msg.saveChanges(); Transport transport = session.getTransport(); //发件人邮箱,授权码(可以在邮箱设置中获取到授权码的信息) transport.connect("xxx@163.com","ltz"); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } } catch (AddressException e) { logger.error("接受邮件地址错误",e); } catch (MessagingException e) { logger.error("发送邮件出现异常",e); } } } subject :这是一个测试程序....
content : 你好!这是我的第一个javamail程序---WQ