在工作中遇到了java发送邮件提醒的需求,下面记录一下这次的开发代码。
public static void sendEmail(String someone, String subject, String content) { Properties props = new Properties(); props.setProperty("mail.host", "smtp.aliyun.com"); //这里是邮箱发件人的配置 props.setProperty("mail.smtp.auth", "true"); Authenticator authenticator = new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("zhangzhiyongali@aliyun.com", "password"); //邮箱发件人的账号密码 } }; Session session = Session.getDefaultInstance(props, authenticator); session.setDebug(true); Message message = new MimeMessage(session); try { message.setFrom(new InternetAddress("zhangzhiyongali@aliyun.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(someone)); //message.setRecipients(RecipientType.TO,InternetAddress.parse("测试的接收的邮件多个以逗号隔开")); try { message.setSubject(subject); message.setContent(content, "text/html;charset=UTF-8"); Transport.send(message); } catch (Exception e) { e.printStackTrace(); } } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } public static void main(String[] args) { //支持群发 sendEmail("zhangjingceshi@umi-game.cn,群发将收件人地址用逗号隔开即可","邮件的标题","测试邮件发送"); System.out.println("发送完成!"); }