JavaMail发送带附件的邮件

本文介绍了一个使用Java实现的邮件发送程序,通过SMTP协议发送带有HTML内容及附件的邮件。该程序利用了JavaMail API和Apache Commons IO库进行文件读取,并使用Log4j记录日志。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test;


import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
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 org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

public class MailSenderImpl {

private static final org.apache.log4j.Logger LOG = Logger.getLogger(MailSenderImpl.class);
   
    private Session session;
    private Transport transport;
   
    public void init() throws Exception{
        this.session = Session.getDefaultInstance(new Properties(), null);
       
        this.transport = session.getTransport("smtp");
       
        this.transport.connect("219.145.110.51", "sendmail@mail.163.com", "123456");
    }
   

   
    public boolean send(String subject, String content, String target){
        try{
           
             System.setProperty("mail.smtp.auth","true");
           
            MimeMessage message =new MimeMessage(session);
           
            /** 发送人地址 */
            Address fromAddress = new InternetAddress("sendmail@mail.163.com");
            message.setFrom(fromAddress);
            message.setReplyTo(new Address[]{fromAddress});
           
            /** 收件人地址 */
            Address toAddress = new InternetAddress(target);           
            message.addRecipient(Message.RecipientType.TO, toAddress);
           
            /** 邮件主题 */
            sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); 
            message.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");
           
            MimeBodyPart messageBodyPart =new MimeBodyPart();

            /** 邮件文本内容 */
//            messageBodyPart.setText("Hi");//邮件正文内容
           
           
            /** 要发送附件的位置 */
            String fileAttachment = "D:/workDoc/iof_8888.xml";
           
           
            /** 邮件引入其它文件内容 */
            DataSource fds = new javax.mail.util.ByteArrayDataSource(content.getBytes(),"text/html");
            messageBodyPart.setDataHandler(new DataHandler(fds));
           
           
            /** 邮件附件 */
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            messageBodyPart = new MimeBodyPart();
            DataSource source =new FileDataSource(fileAttachment);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileAttachment);
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            message.saveChanges();

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

            /** 以下为不带附件的写法 */
//            MimeMessage message = new MimeMessage(session);
//           
//            Address fromAddress = new InternetAddress("sendmail@mail.yimei.com");
//            message.setFrom(fromAddress);
//            message.setReplyTo(new Address[]{fromAddress});
//           
//            Address toAddress = new InternetAddress(target);//gj@yimei.com
//            message.addRecipient(Message.RecipientType.TO, toAddress);
//           
//            sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); 
//            message.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");
//           
//            DataSource fds = new javax.mail.util.ByteArrayDataSource(content.getBytes(),"text/html");
//            message.setDataHandler(new DataHandler(fds));
//           
//            transport.sendMessage(message, message.getAllRecipients());
           
           
            return true;
        }catch(Exception e){
            LOG.error(e.getMessage(),e);
        }
        return false;
    }
   
   
    public void close(){
        try{
            transport.close();
        }catch(Exception e){
        }
    }
   
    public static void main(String[] args) throws Exception{
        long start = System.currentTimeMillis();
        String[] targets = new String[]{"zj@yimei.com","zj@yimei.com","zj@yimei.com","zj@yimei.com","zmfkplj@163.com","zmfkplj@126.com"};
        MailSenderImpl sender = new MailSenderImpl();
        sender.init();
        for(String target:targets){
            sender.send("测试邮件", FileUtils.readFileToString(new File("D:/workDoc/index.html")), target);
        }
        sender.close();
        long end = System.currentTimeMillis();
        System.out.println("elapse time: "+(end-start));
    }
   
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值