java发送邮件
public static boolean sendEmail(){
try {String host = "smtp.163.com"; //发件人使用发邮件的电子信箱服务器
String from = "17623009513@163.com"; //发邮件的出发地(发件人的信箱)
String to = "1790183406@qq.com"; //发邮件的目的地(收件人信箱)
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
// Get session
props.put("mail.smtp.auth", "true"); //这样才能通过验证
MyAuthenticator myauth = new MyAuthenticator("17623009513@163.com", "qweasdzxc123");
Session session = Session.getDefaultInstance(props, myauth);
// session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress(from));
// Set the to address
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set the subject
message.setSubject("小汪汪你好!");
// Set the content
message.setText("这是用java写的发送电子邮件的测试程序!");
message.saveChanges();
for(int i=0;i<100;i++){
System.out.println(i);
Transport.send(message);
}
return true;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
下面是自己建的邮箱内容类
package aa;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MyAuthenticator extends Authenticator{
String userName=null;
String password=null;
public MyAuthenticator(){
}
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}