尝试这个:
String SMTP_HOST_NAME = "mail.domain.com";
String SMTP_PORT = "111";
String SMTP_FROM_ADDRESS="xxx@domain.com";
String SMTP_TO_ADDRESS="yyy@domain.com";
String subject="Textmsg";
String fileAttachment = "C:\\filename.pdf";
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT );
Session session = Session.getInstance(props,new javax.mail.Authenticator()
{protected javax.mail.PasswordAuthentication
getPasswordAuthentication()
{return new javax.mail.PasswordAuthentication("xxxx@domain.com","password");}});
try{
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(SMTP_FROM_ADDRESS));
// create the message part
MimeBodyPart messageBodyPart =
new MimeBodyPart();
//fill message
messageBodyPart.setText("Test mail one");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(multipart);
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(SMTP_TO_ADDRESS));
msg.setSubject(subject);
// msg.setContent(content, "text/plain");
Transport.send(msg);
System.out.println("success....................................");
}
catch(Exception e){
e.printStackTrace();
}
来源: http: //www.coderanch.com/t/586537/java/java/sample-code-java-mail-api