java 发送邮件(qq邮箱作为发件箱,带附件)

最近项目中用到邮件功能,简单的参考网上的,自己修改,写了一下,代码如下:

package mail;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;


import com.sun.mail.util.MailSSLSocketFactory;


public class SendMail {
   private MimeMessage message;
   private Session session;
   private Transport transport;


   private String mailHost = "";
   private String sender_username = "";
   private String sender_password = "";


   private Properties properties = new Properties();


   /*
    * 初始化方法
    */
   public SendMail(boolean debug) {
       InputStream in = SendMail.class.getResourceAsStream("/reportMail.properties");
       try {
           properties.load(in);
           this.mailHost = properties.getProperty("mail.smtp.host");
           this.sender_username = properties.getProperty("mail.sender.username");
           this.sender_password = properties.getProperty("mail.sender.password");
       } catch (IOException e) {
           e.printStackTrace();
       }
        //需要经过授权

       properties.put("mail.smtp.auth", true);

                 //linux上需要添加下面的配置(windows可不加)

                properties.put("mail.smtp.localhost", "127.0.0.1");

       //开启了 SSL 加密,qq邮箱特需的,其他的邮箱好像不用
       MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
       sf.setTrustAllHosts(true);
       properties.put("mail.smtp.ssl.enable", "true");
       properties.put("mail.smtp.ssl.socketFactory", sf);


       session = Session.getInstance(properties);
       //session.setDebug(debug);// 开启后有调试信息
       message = new MimeMessage(session);
   }


   /**
    * 发送邮件
    * 
    * @param subject
    *            邮件主题
    * @param sendHtml
    *            邮件内容
    * @param receiveUser
    *            收件人地址
    * @param attachment
    *            附件
    */
public Boolean doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
    Boolean   flag=true;
   
       try {
           // 发件人
           InternetAddress from = new InternetAddress(sender_username);
           message.setFrom(from);


           //创建邮件的接收地址(数组)
           String[] receivers = null;
    if(receiveUser.contains(";")){
      receivers=receiveUser.split(";");
    }else{
        receivers=new String[1];
        receivers[0]=receiveUser;
    }
//            String[] to=receiveUser.split(";");
          
            //后台也对邮箱做了格式校验,个人认为前台校验就可以了
           String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
           int count =0;
                   for (int i = 0; i < receivers.length; i++)
           {   
                if(receivers[i]!=""&&receivers[i]!=null){
                Pattern regex = Pattern.compile(check);
                        Matcher matcher = regex.matcher(receivers[i]);                      
                       if(matcher.matches()){
                      count=count+1;
                       }
                }
               
         
           }
                  InternetAddress[] sendTo = new InternetAddress[count];
           for (int i = 0; i < receivers.length; i++)
           {
            if(receivers[i]!=""&&receivers[i]!=null){
                Pattern regex = Pattern.compile(check);
                        Matcher matcher = regex.matcher(receivers[i]);
                       if(matcher.matches()){
                      System.out.println("发送到:" + receivers[i]);
                      sendTo[i] = new InternetAddress(receivers[i]);  
                       }
                }
           
           
           }
//            message.setRecipient(Message.RecipientType.TO, sendTo);
           
           message.setRecipients(Message.RecipientType.TO, sendTo);
           
           // 收件人    单个人
//            InternetAddress to = new InternetAddress(receiveUser);
//            message.setRecipient(Message.RecipientType.TO, to);


           // 邮件主题
           message.setSubject(subject);


           // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
           Multipart multipart = new MimeMultipart();
           
           // 添加邮件正文
           BodyPart contentPart = new MimeBodyPart();
           contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
           multipart.addBodyPart(contentPart);
           
           // 添加附件的内容
           if (attachment != null) {
               BodyPart attachmentBodyPart = new MimeBodyPart();
               DataSource source = new FileDataSource(attachment);
               attachmentBodyPart.setDataHandler(new DataHandler(source));
               
               //MimeUtility.encodeWord可以避免文件名乱码
               attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
               multipart.addBodyPart(attachmentBodyPart);
           }
           
           // 将multipart对象放到message中
           message.setContent(multipart);
           // 保存邮件
           message.saveChanges();


           transport = session.getTransport("smtp");
           // smtp验证,就是你用来发邮件的邮箱用户名密码
           transport.connect(mailHost, sender_username, sender_password);
           // 发送
           transport.sendMessage(message, message.getAllRecipients());


           System.out.println("send success!");
       } catch (Exception e) {
           e.printStackTrace();
           flag=false;
       } finally {
           if (transport != null) {
               try {
                   transport.close();
               } catch (MessagingException e) {
                   e.printStackTrace();
                   flag=false;
               }
           }
       }
       return flag;
   }


   public static void main(String[] args) throws IOException {
    SendMail se = new SendMail(true);
    InputStream in = SendMail.class.getResourceAsStream("/reportMail.properties");
    Properties properties = new Properties();
    properties.load(in);
        String receives = properties.getProperty("mail.receivers");
         File sendFilePath = new File("D://Down//2016-04-22.zip");
       se.doSendHtmlEmail("这时8月日报", "你好啊,happybao,这是8月的报表!",  receives, sendFilePath);
   }
}

以下是配置文件:

 mail.smtp.host=smtp.qq.com
mail.sender.username=XXX@qq.com
mail.sender.password=XXX
mail.receivers=XXX@qq.com;XXX@163.com

   好了,这样,邮件发送,就ok了!

 需要注意的是:发件箱的密码,不是你登录QQ的密码,是你开始pop3服务的授权码:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值