javamail发送附件 源码 [转贴 2006-02-26 23:50:45 ] 发表者: 蒙面猪头

javamail发送附件 源码 [转贴 2006-02-26 23:50:45 ] 发表者: 蒙面猪头

在网上找了好多例子进行实验发现大多都不好用 因为现在的邮件服务器很少有不需要验证的 而网上提供的代码例子大都用的是无需验证邮件服务器提供的方法 下面是我一个测试无误的例子供大家参考

 

package  untitled4;

import  java.util.Properties;
import  javax.mail. * ;
import  javax.mail.internet. * ;
import  javax.activation. * ;

 
class  AttachExamplea6  {
  
public static void main (String args[])
      
throws Exception {
    String host 
= "smtp.tom.com";//邮件服务器的SMTP服务  我注册的是www.tom.com信箱服务器
    String from = "[email protected]";//从哪个信箱发送 该信箱一般必须为邮件服务器提供注册的信箱
    String to = "[email protected]";//发送给谁
    String fileAttachment = "D:\\123123.txt";//要发送附件的位置
    System.setProperty("mail.smtp.auth","true");//这句话必须加 否则服务器验证一般都会提示验证失败 这个让我苦恼了不少时间
    
// Get system properties
    Properties props = System.getProperties();

    
// Setup mail server
    props.put("mail.smtp.host", host);

    
// Get session
    Session session =
      Session.getInstance(props, 
null);

    
// Define message
    MimeMessage message =
      
new MimeMessage(session);
    message.setFrom(
      
new InternetAddress(from));
    message.addRecipient(
      Message.RecipientType.TO,
      
new InternetAddress(to));
    message.setSubject(
      
"Hello JavaMail Attachment");

    
// create the message part
    MimeBodyPart messageBodyPart =
      
new MimeBodyPart();

    
//fill message
    messageBodyPart.setText("Hi");//邮件正文内容

    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
    message.setContent(multipart);
    message.saveChanges();
    Transport transport 
= session.getTransport("smtp");
           
// transport.connect();
            transport.connect(host, 25"caoshibin""wangyss");//发信服务器,自己信箱的用户名,密码
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

    
// Send the message
 
//   Transport.send( message );
  }

}


你可能感兴趣的:(javamail发送附件 源码 [转贴 2006-02-26 23:50:45 ] 发表者: 蒙面猪头)