java mail api 使用
所需要的jar包: http://pan.baidu.com/s/1qWGZRJm
如果遇到这个错误:在windows防火墙允许 javaw.exe访问网络.或者关闭防火墙
FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197) ERROR: transport error 202: connect failed: Connection timed out ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510) JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [../../../src/share/back/debugInit.c:750]
如果你使用qq邮箱,将会遇到这个错误
454 Authentication failed, please open smtp flag first!
在QQ邮箱的设置里面,找到账户-> POP3/IMAP/SMTP选择开启POP3/SMTP服务
package study; import java.util.Date; import java.util.Properties; import java.util.Scanner; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class email { public static void main(String [] args) throws MessagingException { final String userName="1653157218@qq.com"; //设置发件人用户名 final String password="*********"; //设置发件人密码 Properties pro=new Properties(); pro.put("mail.smtp.host", "smtp.qq.com"); // 设置发送邮件端口号 pro.put("mail.smtp.port", "25"); // 设置邮件发送需要认证 pro.put("mail.smtp.auth", "true"); // 创建邮件验证信息,即发送邮件的用户名和密码 Authenticator authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { // 重写验证方法,填写用户名,密码 return new PasswordAuthentication(userName, password); } }; // 根据邮件会话 构建一个邮件的session Session sendMailSession = Session.getDefaultInstance(pro, authenticator); // 创建一个邮件消息 Message message = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address sourceAddress = new InternetAddress(userName); // 将原地址设置到消息的信息中 message.setFrom(sourceAddress); // 创建邮件的接收者地址 Address destAddress = new InternetAddress("dbyl@dbyl.cn"); // 将接收者的地址设置到消息的信息中 message.setRecipient(Message.RecipientType.TO, destAddress); // 设置邮件的主题 message.setSubject("Merry Christmas!"); // 设置邮件的发送内容 message.setText("Hi there,Merry Christmas!"); Transport.send(message);; System.out.print("your Email send successful\n"); } }
转载请注明出处:http://www.cnblogs.com/tobecrazy/
![](https://images2015.cnblogs.com/blog/418763/201610/418763-20161014225758390-402578379.gif)