package com.souvc.mail;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
private static SendMail instance = null;
private SendMail() {
}
public static SendMail getInstance() {
if (instance == null) {
instance = new SendMail();
}
return instance;
}
public void send() {
try {
// 接收者的邮箱
String to[] = { "XX@qq.com" };
// 配置发送邮箱的配置--
Properties p = new Properties();
p.put("mail.smtp.auth", "true");
p.put("mail.transport.protocol", "smtp");
p.put("mail.smtp.host", "smtp.163.com");
p.put("mail.smtp.port", "25");
// 建立会话
Session session = Session.getInstance(p);
// 建立信息
Message msg = new MimeMessage(session);
// 发件人
msg.setFrom(new InternetAddress("XX@163.com"));
// 收件人
String toList = getMailList(to);
InternetAddress[] iaToList = new InternetAddress().parse(toList);
msg.setRecipients(Message.RecipientType.TO, iaToList);
// 发送日期
msg.setSentDate(new Date());
// 主题
msg.setSubject("测试邮件");
// 内容
msg.setText("注意,这是测试程序发的,请不要回复!");
// 邮件服务器进行验证
Transport tran = session.getTransport("smtp");
// *配置发送者的邮箱账户名和密码
tran.connect("smtp.163.com", "XX@163.com", "mima");
// 发送
tran.sendMessage(msg, msg.getAllRecipients());
System.out.println("邮件发送成功");
} catch (Exception e) {
e.printStackTrace();
}
}
private String getMailList(String[] mailArray) {
StringBuffer toList = new StringBuffer();
int length = mailArray.length;
if (mailArray != null && length < 2) {
toList.append(mailArray[0]);
} else {
for (int i = 0; i < length; i++) {
toList.append(mailArray[i]);
if (i != (length - 1)) {
toList.append(",");
}
}
}
return toList.toString();
}
public static void main(String[] args) {
SendMail sendMail = SendMail.getInstance();
sendMail.send();
// System.out.println(System.nanoTime());
// UUID uuid = UUID.randomUUID();
// System.out.println(uuid);
}
}