邮件发送工具类
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; import javax.mail.internet.MimeMessage.RecipientType; public class MailUtil { private static String smtp_host = "smtp.yeah.net"; private static String username = "***@yeah.net"; private static String password = "****"; private static String from = "****"; public static void main(String[] args) { MailUtil.sendMail("测试邮件", "测试邮件内用", "***@qq.com"); } public static void sendMail(String subject, String content, String to) { Properties prop = new Properties(); prop.setProperty("mail.smtp.host", smtp_host); prop.put("mail.transport.protocol", "smtp"); prop.setProperty("mail.smtp.auth", "true"); Session session = Session.getInstance(prop); Message mes = new MimeMessage(session); try { // 设置从哪发 mes.setFrom(new InternetAddress(from)); // 设置接收者 mes.setRecipient(RecipientType.TO, new InternetAddress(to)); // 邮件主题 mes.setSubject(subject); // 邮件内容 mes.setContent(content, "text/html;charset=utf-8"); // 发送对象 Transport transport = session.getTransport(); // 对象邮件协议,用户名,授权码, transport.connect(smtp_host, username, password); // 获取所有邮件发送者,发送邮件 transport.sendMessage(mes, mes.getAllRecipients()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("邮件发送失败"); } } }