<span style="white-space:pre"> </span>@Test public void fun() throws AddressException, MessagingException { Properties props = new Properties(); props.setProperty("mail.host", "smtp.163.com"); props.setProperty("mail.smtp.auth", "true"); //发件邮箱验证 Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("qq83986976", "3854928"); } }; //得到session Session session = Session.getInstance(props, auth); //创建MimeMessage MimeMessage msg = new MimeMessage(session); //设置发件人 msg.setFrom(new InternetAddress("qq83986976@163.com")); /* * 设置收件人 * to收件人 * cc抄送 * bcc暗送 */ msg.setRecipients(RecipientType.TO, "83986976@qq.com"); msg.setSubject("测试邮件"); msg.setContent("邮件测试", "text/html;charset=utf-8"); Transport.send(msg); }
发送带有附件的邮件
public void fun2() throws AddressException, MessagingException, IOException { Properties props = new Properties(); props.setProperty("mail.host", "smtp.163.com"); props.setProperty("mail.smtp.auth", "true"); Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("qq83986976", "3854928"); } }; //得到session Session session = Session.getInstance(props, auth); //创建MimeMessage MimeMessage msg = new MimeMessage(session); //设置发件人 msg.setFrom(new InternetAddress("qq83986976@163.com")); msg.setRecipients(RecipientType.TO, "83986976@qq.com"); msg.setSubject("我的附件测试"); /* * 发送附件, * 1多部件的部件内容,MimeMultipart * 2个主体 */ MimeMultipart list = new MimeMultipart(); //创建MimeBodyPart MimeBodyPart part1 = new MimeBodyPart(); part1.setContent("附件邮件","text/html;charset=utf-8"); //添加部分 list.addBodyPart(part1); MimeBodyPart part2 = new MimeBodyPart(); part2.attachFile(new File("F:/党员.png")); //显示在附件上,并处理乱码 part2.setFileName(MimeUtility.encodeText("党员.png")); list.addBodyPart(part2); msg.setContent(list); Transport.send(msg); }