首页 > 新闻动态 >  

新闻动态
NEWS

java 带文件的 邮件发送

添加时间:2013-5-10 点击量:

带文件上传的简单邮件发送案例,这个案例还得导入mail.jar包,这个可以去百度上download一个.


此中要重视的是:


①:name-->只是个名字,不要带上@什么的,


②:smtp的地址:QQ邮箱-->smtp.qq.com


        163邮箱-->smtp.163.com


        126邮箱-->smtp.126.com


        yeah邮箱-->smtp.yeah.net


 即:smtpServer参数



package com.email;


import javax.mail.;


import javax.mail.internet.;


import java.util.;


import javax.activation.;


public class BaseMail {  


private int count=1;  


Transport transport=null;    


/   发送邮件  


@param smtp办事器  例:smtp.exmail.qq.com  


@param 用户名  


@param 暗码  


@param 发件人邮箱地址  


@param 收信人邮箱地址  


@param 邮件题目  


@param 邮件正文  


@param 附件地址  


/  


public boolean sendMail(String smtpServer, String name, String password,    String meMail, String toMail, String mailTitle, String mailText  String fileName  ) {  


 long begin=System.currentTimeMillis();   


Properties props = System.getProperties();   // 设置smtp办事器   


props.setProperty(mail.smtp.host, smtpServer);   // 如今的大项目组smpt都须要验证了  


props.put(mail.smtp.auth, true);


Session s = Session.getInstance(props);   // 为了查看运行时的信息   


// 由邮件会话新建一个消息对象   


MimeMessage message = new MimeMessage(s);  


 try {  


  // 发件人   


 InternetAddress = new InternetAddress(meMail);   


 message.setFrom();  


  // 收件人   


 InternetAddress to = new InternetAddress(toMail);   


 message.setRecipient(Message.RecipientType.TO, to);    


// 邮件题目     


message.setSubject(mailTitle);  


  // String content = 测试内容;   


 // 邮件内容,也可以使纯文本text/plain


 // message.setContent(content, text/html;charset=GBK);


 // 下面代码是发送附件  


 // String fileName = d://hello.txt;    


MimeBodyPart messageBodyPart = new MimeBodyPart();   


 messageBodyPart.setText(mailText);   


 Multipart multipart = new MimeMultipart();  


  multipart.addBodyPart(messageBodyPart);


   messageBodyPart = new MimeBodyPart();


//上传文件


if (null != fileName) {


   DataSource source = new FileDataSource(fileName);


     messageBodyPart.setDataHandler(new DataHandler(source));


    messageBodyPart.setFileName(fileName.substring(fileName.lastIndexOf(/)+1));


    multipart.addBodyPart(messageBodyPart);


 }


   message.setContent(multipart);


   message.saveChanges();    transport = s.getTransport(smtp);    // smtp验证,就是你用来发邮件的邮箱用户名暗码  


  transport.connect(smtpServer, name, password);    // 发送    


transport.sendMessage(message, message.getAllRecipients());    


return true;  


 } catch (Exception e) {  


  e.printStackTrace();


  }finally{    


try {


   transport.close();   


 } catch (MessagingException e) {   


  e.printStackTrace();  


  }


  }   


return false;


 }    


public static void main(String[] args) {   


BaseMail mail = new BaseMail();   


mail.sendMail(smtp.yeah.net, 12345, password, 12345@yeah.net, 接管人的邮件地址, 题目, 内容,文件地址);  }


}

我们永远不要期待别人的拯救,只有自己才能升华自己。自己已准备好了多少容量,方能吸引对等的人与我们相遇,否则再美好的人出现、再动人的事情降临身边,我们也没有能量去理解与珍惜,终将擦肩而过。—— 姚谦《品味》
分享到: