public class SendEmail
{
/**
* 做该例子出现的异常
* 1、Exception in thread "main" java.lang.NoClassDefFoundError:
* com/sun/mail/util/LineInputStream
*(将javaee5换成jvaee6)
* 2、Could not connect to SMTP host: localhost, port: 25
*(是端口号设置不正确,用哪个邮箱发送邮件就要设置相应的smtp host,例如,163的是smtp.163.com)
* 3、553 Local user only,163 smtp4,DtGowAAXE1vW5kBYngBsIQ--.47014S2 1480648406
* (设置的发送邮箱和端口不对应)
* 4、553 authentication is required,163 smtp4,DtGowACH2ywr50BYJRlsIQ--.16129S2 1480648491
* (这里用163邮箱发送需要验证)
* 设置property.put("mail.smtp.auth","true")注意,不是property.put("mail.smtp.auth",true)
* 重写Authenticator类的getPasswordAuthentication方法设置用户名和密码
* @param args
*/
public static void main(String[] args)
{
final String from = "XXX@163.com";
final String pass = "XXX";
String to = "XXX@qq.com";
String host = "smtp.163.com";
Properties property = System.getProperties();
property.setProperty("mail.smtp.host", host);
property.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(property,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(from,pass);
}
});
MimeMessage message = new MimeMessage(session);
try
{
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("this is subject");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("<a href=\"www.baidu.com\">点击此处</a>","text/html");
Multipart mutipart = new MimeMultipart();
mutipart.addBodyPart(messageBodyPart);
/*附件部分*/
messageBodyPart = new MimeBodyPart();
String filename = "D:/Test/email.ser";
DataSource dataSource = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(dataSource));
messageBodyPart.setFileName(filename);
mutipart.addBodyPart(messageBodyPart);
message.setContent(mutipart);
Transport.send(message);
System.out.println("the email is send successful!");
}
catch( AddressException e )
{
e.printStackTrace();
}
catch( MessagingException e )
{
e.printStackTrace();
}
}
}