Java 邮件email 发送, 邮件内容、邮件附件 名称 乱码处理 完整版

/**
 *
 *
 *
 * Copyright (C) Corporation. All rights reserved.
 *
 */

package org.email.send;

import java.io.File;
import java.util.*;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
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 org.apache.commons.mail.ByteArrayDataSource;



/**
 * 邮件发送类
 * 需要的jar包有:mail.jar ,activation.jar ,
 * 如果用到ByteArrayDataSource 类需要引入 commons-email.jar ;

 *
 */
public class SendEMailMessage  {



    private String senderEmailAddr;
    
    //发送者别名
    private String displayName;
    
    // 邮件发送者邮箱用户
    private String smtpUserName;

    // 邮件发送者邮箱密码
    private String smtpPassword;

    // 邮件发送者邮箱SMTP服务器
    private String smtpServerName;

    // 邮件发送者邮箱SMTP服务器端口
    private String smtpServerPort;

    // 传输类型
    private String transportType;

    //是否验证
    private Boolean isAuth;
    
    private int timeout;
    // 属性
    private static Properties props;

    
     public static void main(String [] args){
        SendEMailMessage sem = new SendEMailMessage();
        sem.init();
        sem.send();
    }

    
    public void init() {
        // 设置邮件发送者地址
        this.senderEmailAddr = "xxyy@163.com";
        //发送者别名
        this.displayName="管理员";
        // 设置邮件发送者邮箱SMTP服务器
        this.smtpServerName = "smtp.163.com";
        // 设置邮件发送者邮箱SMTP服务器端口号
        this.smtpServerPort = "25";
        // 设置邮件发送者邮箱用户
        this.smtpUserName = "testAdmin@163.com";
        // 邮件发送者邮箱密码
        this.smtpPassword = "password";
        // 设置传输类型
        this.transportType = "smtp";
        
        this.isAuth = true;
        
        this.timeout = 300000;
        
        props = new Properties();
        // 存储发送邮件服务器的信息
        props.put("mail.smtp.host", smtpServerName);
        props.put("mail.smtp.port", smtpServerPort);
        props.put("mail.transport.protocal", transportType);
        props.put("mail.smtp.auth", isAuth ? "true":"false");
        props.put("mail.stmp.timeout", timeout);
    }

    private Session getSession(){
        Authenticator authenticator = null;
        if(isAuth){
            authenticator = new SimpleAuthenticator(smtpUserName,smtpPassword);
        }
        Session sendMailSession = Session.getDefaultInstance(props,authenticator);
        
        return sendMailSession;
    }
    

    
    /**
     * 发送email
     * @param msg
     * @return
     */
    public void send(){
        Session session = this.getSession();//获取邮件服务器连接
        Message message = new MimeMessage(session);//创建邮件
        
        try {
            Address from =  new InternetAddress(senderEmailAddr,displayName);
            message.setFrom(from);//发件人
            message.setSubject("邮件主题");
            message.setSentDate(new Date());//发送时间
            
            List<File> attach = new ArrayList<File>();//附件,此处附件没有文件,只是为了方便示例。
            
            Multipart multiPart = new MimeMultipart();
            
            BodyPart context = new MimeBodyPart();    
            context.setContent("<html><body><a herf='http://www.baidu.com'>This is a test email ! helloworld..</a><body></html>","text/html;charset=utf-8");
            multiPart.addBodyPart(context);
            
            for(File att:attach){
                
                MimeBodyPart attachmentPart = new MimeBodyPart();  
                //1.如果数据源是byte[]
               // DataSource fds = new ByteArrayDataSource(byte[] b,"application/octet-stream");
                
                //2.如果内容是file
                DataSource fds = new FileDataSource(att);
                attachmentPart.setDataHandler(new DataHandler(fds));  
                attachmentPart.setFileName(MimeUtility.encodeText(att.getName(),"utf-8",null));  // 解决附件名称乱码
                
                multiPart.addBodyPart(attachmentPart);
            }
            
            message.setContent(multiPart);
            
            message.setRecipients(RecipientType.TO, new Address[]{new InternetAddress("1111@163.com")});//发送
            message.setRecipients(RecipientType.CC, new Address[]{new InternetAddress("2222@163.com")});//抄送
            message.setRecipients(RecipientType.BCC, new Address[]{new InternetAddress("333@163.com")});//暗送
            //发送邮件
            Transport.send(message);
            
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//======================================================================
    class SimpleAuthenticator extends Authenticator {
        private String user;
        private String pwd;

        public SimpleAuthenticator(String user, String pwd) {
            this.user = user;
            this.pwd = pwd;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, pwd);
        }
    }
    
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值