JavaMail 发送Email(含附件)

JavaMail 发送邮件有固定的步骤,按照固定的步骤设置好送信所需要的信息之后,就可以送信了。本文主要讨论使用JavaMail发送含有多个附件的Email,对于Email的正文内容,不是本文的重点。以后会讨论使用JavaMail+Velocity模版来发送指定形式的Email。
首先需要一个MailInfo来存放送信所需要的信息。这里省略了Setter和Getter方法。

public class MailInfo {
    //邮件服务器Ip
    private String mailServerHost;
    //邮件服务器端口号
    private String mailServerPort = "25";
    //邮件来源地址(发件人邮箱地址)
    private String fromAddress;    
    // 邮件接收者的地址(收件人邮箱地址)
    private String toAddress;
    // 登陆邮件发送服务器的用户名和密码    
    private String userName;    
    private String password; 
    // 是否需要身份验证    
    private boolean validate = false;    
    // 邮件主题    
    private String subject;    
    // 邮件的文本内容    
    private String content;
    //附件
    private List<String> attachFileNames;
    //Setter Getter 方法省略了
    }

密码校验类

public class MyAuthenticator extends Authenticator{
    private String userName;
    private String password;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public MyAuthenticator(){

    }

    public MyAuthenticator(String userName,String password){
        this.userName = userName;
        this.password = password;
    }
    /**
     * check 密码
     */
    public PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication(userName,password);
    }

}

送信的封装和测试

public class MailSendWithFiles {
    /**
     * 
     * @param mailInfo
     * @return
     * 发送含有多个附件的email,multipart中存BodyPart ,BodyPart
     * 中存放邮件的的正文,和附件等信息。
     * multipart 中可以包含多个BodyPart,
     * 一个BodyPart 中存放一个附件
     * 注意至关重要的一步,设置附件的名称,
     * bodypart.setFileName(file.getName());
     * 如果不设置附件名称,可以送信成功,但是邮件中附件的名字和后缀都
     * 是让你头痛的。
     */
    public boolean SendMail(MailInfo mailInfo){
        //构建Session需要的信息
        Properties p = new Properties();
        p.put("mail.smtp.host", mailInfo.getMailServerHost());    
        p.put("mail.smtp.port", mailInfo.getMailServerPort());    
        p.put("mail.smtp.auth", "true");
        //Auth验证
        MyAuthenticator myAuthenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());

        Session session = Session.getDefaultInstance(p, myAuthenticator);
        try {    
          // 通过session构建Message  
          Message mailMessage = new MimeMessage(session);    
          // 发件人    
          Address from = new InternetAddress(mailInfo.getFromAddress());    
          mailMessage.setFrom(from);    
          // 收件人
          Address to = new InternetAddress(mailInfo.getToAddress());    
          mailMessage.setRecipient(Message.RecipientType.TO,to);    
          // 邮件主题
          mailMessage.setSubject(mailInfo.getSubject());    
          // 邮件时间
          mailMessage.setSentDate(new Date());    
          // 
          Multipart multipart = new MimeMultipart();

          //邮件内容
          BodyPart bodyPart1 = new MimeBodyPart();
          bodyPart1.setText(mailInfo.getContent());
          multipart.addBodyPart(bodyPart1);

          //邮件附件
          List<String> attachFileNames = mailInfo.getAttachFileNames();
          if(attachFileNames!=null&&attachFileNames.size()>0){
            for(String s :attachFileNames){
                  File file = new File(s);
                  BodyPart bodyPart2 = new MimeBodyPart();
              DataSource source = new FileDataSource(file);
              bodyPart2.setDataHandler(new DataHandler(source));  
              //至关重要的一步,设置邮件中附件的名称,不设置附件的
              //名称为*******.bin 这显然不是我们想要的
              bodyPart2.setFileName(file.getName());
              multipart.addBodyPart(bodyPart2);
              }
          }


          mailMessage.setContent(multipart);

          // 发送邮件    
          Transport.send(mailMessage);   
          return true;    
          } catch (MessagingException ex) {    
              ex.printStackTrace();    
          }
        return false;
    }

    public static void main(String[] args){
        MailInfo mailInfo = new MailInfo();
         mailInfo.setMailServerHost("smtp.163.com");    
         mailInfo.setMailServerPort("25");    
         //mailInfo.setValidate(true);    
         mailInfo.setUserName("k****@163.com");    
         mailInfo.setPassword("***********");
         mailInfo.setFromAddress("kshrimp@163.com");    
         mailInfo.setToAddress("1******@qq.com");    
         mailInfo.setSubject("ceshi");    
         mailInfo.setContent("Hello!ggggg");

         //设置附件
         List<String> attachFileNames = new ArrayList<String>();
         attachFileNames.add("G:\\1.properties");
         attachFileNames.add("G:\\2.txt");
         attachFileNames.add("G:\\mail.vm");

         mailInfo.setAttachFileNames(attachFileNames);

        MailSendWithFiles m  = new MailSendWithFiles();
        m.SendMail(mailInfo);
    }
}
在测试的过程中,曾经忽略了设置附件的名称,结果出现了问题,在附件中附件总是显示为****.bin 的文件,但是下载附件修改后缀之后仍然可以使用。后来发现是没有设置附件名的缘故。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值