java 代码发邮件怎么添加附件

如题所述

实现java发送邮件的过程大体有以下几步:

准备一个properties文件,该文件中存放SMTP服务器地址等参数。

利用properties创建一个Session对象

利用Session创建Message对象,然后设置邮件主题和正文

利用Transport对象发送邮件

需要的jar有2个:activation.jar和mail.jar发送附件,需要用到Multipart对象。

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

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;

public class JavaMailWithAttachment {
    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 JavaMailWithAttachment(boolean debug) {
        InputStream in = JavaMailWithAttachment.class.getResourceAsStream("MailServer.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();
        }

        session = Session.getInstance(properties);
        session.setDebug(debug);// å¼€å¯åŽæœ‰è°ƒè¯•ä¿¡æ¯
        message = new MimeMessage(session);
    }

    /**
     * å‘送邮件
     * 
     * @param subject
     *            é‚®ä»¶ä¸»é¢˜
     * @param sendHtml
     *            é‚®ä»¶å†…容
     * @param receiveUser
     *            æ”¶ä»¶äººåœ°å€
     * @param attachment
     *            é™„件
     */
    public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
        try {
            // å‘件人
            InternetAddress from = new InternetAddress(sender_username);
            message.setFrom(from);

            // æ”¶ä»¶äºº
            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就可以很方便的搞定
                // è¿™é‡Œå¾ˆé‡è¦ï¼Œé€šè¿‡ä¸‹é¢çš„Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
                //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");
                
                //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();
        } finally {
            if (transport != null) {
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        JavaMailWithAttachment se = new JavaMailWithAttachment(true);
        File affix = new File("c:\\测试-test.txt");
        se.doSendHtmlEmail("邮件主题", "邮件内容", "[email protected]", affix);//
    }
}
温馨提示:答案为网友推荐,仅供参考
相似回答