import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.activation.*;
public class Mail {
public static void main(String[] args) {
Properties props = System.getProperties();
// 设置smtp服务器
props.setProperty("mail.smtp.host", "smtp.163.com");
// 现在的大部分smpt都需要验证了
props.put("mail.smtp.auth", "true");
Session s = Session.getInstance(props);
// 为了查看运行时的信息
s.setDebug(true);
// 由邮件会话新建一个消息对象
MimeMessage message = new MimeMessage(s);
try {
// 发件人
InternetAddress from = new InternetAddress("
test@163.com");
message.setFrom(from);
// 收件人
InternetAddress to = new InternetAddress("
test@126.com");
message.setRecipient(Message.RecipientType.TO, to);
// 邮件标题
message.setSubject("test");
String content = "测试内容";
// 邮件内容,也可以使纯文本"text/plain"
message.setContent(content, "text/html;charset=GBK");
/****下面代码是发送附件******
String fileName = "d://hello.txt";
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Hi");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileName);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);*/
message.saveChanges();
Transport transport = s.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect("smtp.163.com", "test", "pwd");
// 发送
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}