利用Java发送邮件的过程主要有一下步骤:
需要的jar有2个:activation.jar和mail.jar
代码如下(这里我以网易163邮箱为例):
public class SendMailUtil { /** * 发送邮件 * @param to 邮箱收件人 */ public static void sendMail(String to){ boolean isSSL = true; String host = "smtp.163.com"; int port = 465; String from = "[email protected]"; boolean isAuth = true; final String username = "[email protected]";//邮箱账号 final String password = "********";//这里的密码指的是邮箱授权码,下边会有介绍 //1、创建session,配置属性 Properties props = new Properties(); props.put("mail.smtp.ssl.enable", isSSL); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", isAuth); Session session = Session.getDefaultInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); //2、创建邮件对象 try{ Message message=new MimeMessage(session); message.setFrom(new InternetAddress(from));//邮件的发送人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));//邮件的收件人 message.setSubject("主题");//邮件主题也就是标题 message.setContent("邮件的正文", "text/html;charset=UTF-8"); //3、发送邮件 Transport.send(message); }catch (Exception e) { e.printStackTrace(); } } /** * 测试方法 * @param args */ public static void main(String[] args) { sendMail("[email protected]"); } }遇到的问题:(如果上边邮箱密码你写的不是授权码就会报这个错)
解决方法:
1、需要到你的邮箱中开启服务:开启POP3服务 和 SMTP服务
然后要发短信绑定手机,设置客户端授权密码 ,这里的授权密码就是上边所说的授权密码。
2、确保POP3服务和SMTP服务都选择上,设置完成后,问题也就解决了。