1.导入 activation.jar mail.jar
SendEmail 类:
package mail2;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* @author Sech
*
*/
public class SendEmail {
/**
*
*/
public SendEmail() {
// TODO Auto-generated constructor stub
}
/**
* 发送Email
*/
public void Send(String content) {
try {
String host = "127.0.0.1";
String from = "[email protected]";// 发送的邮箱
String to = "[email protected]";// 接收的邮箱
String userName = "111";// 发送邮箱的用户名
String password = "123";// 发送邮箱的密码
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("username", userName);
// props.put("mail.smtp.port", "587");
/**
* props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
*/
props.put("password", password);
SmtpAuth sa = new SmtpAuth();
sa.setUserinfo(userName, password);
Session session = Session.getDefaultInstance(props, sa);
// Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
message.setSubject("网站回复");
message.setContent(content, "text/plain");
Address sendaddress = new InternetAddress(from);
Address toAddress = new InternetAddress(to);
message.setFrom(sendaddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.saveChanges(); // implicit with send()
Transport.send(message);
// System.out.println("success!");
} catch (MessagingException e) {
System.out.println("send" + e.getMessage());
}
}
}
2.SmtpAuth类 验证的,装账号和密码的
package mail2;
import javax.mail.Authenticator;
/**
* @author Sech
*
*/
public class SmtpAuth extends Authenticator {
private String user, password;
public void setUserinfo(String getuser, String getpassword) {
user = getuser;
password = getpassword;
}
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(user, password);
}
}