public static void main(String[] args) {
try{
System.out.println("开始发送邮件......");
// 创建邮件客户端对象
MailClient mailClient = new MailClient("smtp.163.com",// 邮件服务器Ip地址
"15711064834@163.com",// 发件人邮箱
"2515625456@QQ.com",// 收件人邮箱
"Hello,Hello,Hello,Hello,Hello,Hello,",// 邮件标题
"Hello,Hello,Hello,Hello",// 邮件内容
"15711064834@163.com",// 登录帐号
"123123123.."// 登录密码
);
// 发送邮件
mailClient.sendEmail();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("邮件发送完毕。");
}
public void sendEmail() {
// 创建属性对象
Properties properties = System.getProperties();
// 设置属性值
properties.put("mail.smtp.host", mailServerIp);// 邮件服务器
properties.put("mail.smtp.auth", "true");// 安全验证
// 创建session对象
Session mailSession = Session.getInstance(properties,
new Authenticator() {
// 返回封装帐号密码的对象
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
// 邮件对象
Message message = new MimeMessage(mailSession);
// 设置发件人
message.setFrom(new InternetAddress(fromEmail));
// 设置收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(
toEmail));
// 设置邮件主题
message.setSubject(emailSubject);
// 设置邮件内容
message.setContent(emailContent, "text/html;charset=utf-8");
// 设置发送日期
message.setSentDate(new Date());
// 创建邮件传输对象
Transport transport = mailSession.getTransport("smtp");
// 发送邮件
transport.send(message);
// 关闭
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 邮件服务器的Ip地址
protected String mailServerIp = null;
// 发件人
protected String fromEmail = null;
// 收件人
protected String toEmail = null;
// 邮件标题
protected String emailSubject = null;
// 邮件内容
protected String emailContent = null;
// 登录帐号
protected String userName = null;
// 登录密码
protected String password = null;
public MailClient() {
}
public MailClient(String mailServerIp, String fromEmail, String toEmail,
String emailSubject, String emailContent, String userName,
String password) {
super();
this.mailServerIp = mailServerIp;
this.fromEmail = fromEmail;
this.toEmail = toEmail;
this.emailSubject = emailSubject;
this.emailContent = emailContent;
this.userName = userName;
this.password = password;
}
//控制台报错
//开始发送邮件......
//javax.mail.SendFailedException: Sending failed;
// nested exception is:
// class javax.mail.AuthenticationFailedException
//邮件发送完毕。
// at javax.mail.Transport.send0(Transport.java:218)
// at javax.mail.Transport.send(Transport.java:80)
// at org.gjgx.web.MailClient.sendEmail(MailClient.java:82)
// at org.gjgx.web.MailClient.main(MailClient.java:35)