Java 发送 Email

package test;


import java.io.UnsupportedEncodingException;
import java.util.List;


import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
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.lang.StringUtils;


public class WithAttachmentMessage {


    /**
    * 根据传入的文件路径创建附件并返回
    * @param fileName 福建了路径
    * @return
    * @throws MessagingException
    */
    public static MimeBodyPart createAttachment(String fileName) throws MessagingException{
        MimeBodyPart part = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(fileName);
        part.setDataHandler(new DataHandler(fds));
        part.setFileName(fds.getName());
        return part;
    }

    /**
    * 根据传入的邮件正文和文件路径构建图文并茂的正文
    * @param body 邮件正文
    * @param fileName 图片路径
    * @return
    * @throws MessagingException
    */
    public static MimeBodyPart createContent(String body, String fileName) throws MessagingException{
        //用于保存最终正文部分
        MimeBodyPart contentBody = new MimeBodyPart();
        // 用于组合正文与图片,"related"型的MimeMultipart对象
        MimeMultipart contentMulti = new MimeMultipart("related");

        // 正文的文本部分
        MimeBodyPart textBody = new MimeBodyPart();
        textBody.setContent(body, "text/html;charset=utf-8");
        contentMulti.addBodyPart(textBody);

        //正文的图片部分
        MimeBodyPart jpgBody = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(fileName);
        jpgBody.setDataHandler(new DataHandler(fds));
        jpgBody.setContentID("logo_jpg");
        contentMulti.addBodyPart(jpgBody);

        //将上面的"related"型的MimeMultipart对象作为邮件正文
        contentBody.setContent(contentMulti);
        return contentBody;
    }

    /**
    * 根据传入的 Seesion 对象创建混合型的 MIME消息
    * @param session
    * @param nick 发件人昵称
    * @param from 发件人邮箱地址
    * @param headName 邮件标题
    * @param receiveUser 收件人
    * @param bodyParts  邮件内容
    *  List<MimeBodyPart>
    * @return
    * @throws AddressException
    * @throws MessagingException
    * @throws UnsupportedEncodingException 
    */
    public MimeMessage createMessage(Session session,String nick, String from, String headName, String receiveUser, List<MimeBodyPart> bodyParts) throws AddressException, MessagingException, UnsupportedEncodingException{
        MimeMessage msg = new MimeMessage(session);
        //设置发件人昵称
        String nickStr = "";
        if(StringUtils.isBlank(nick)){
        nickStr = "未知帐号";
        }else{
        nickStr = MimeUtility.encodeText(nick);
        }
        msg.setFrom(new InternetAddress(nickStr + " <" + from + ">"));//发件人
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(receiveUser));//收件人
        msg.setSubject(headName);//邮件标题

        //判断邮件内容
        if(bodyParts == null || bodyParts.size() == 0){
        return null;
        }

        // 设置正文与附件之间的关系
        MimeMultipart allPart = new MimeMultipart();
        for(MimeBodyPart mbp : bodyParts){
        allPart.addBodyPart(mbp);
        }
        allPart.setSubType("mixed");

        // 将上面混合型的 MimeMultipart 对象作为邮件内容并保存
        msg.setContent(allPart, "text/html;charset=utf-8");
        msg.saveChanges();
        return msg;
    }
}
package test;


import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;


public class MessageSender {

// 设置服务器
    private static String KEY_SMTP = "mail.smtp.host";
    private static String VALUE_SMTP = "smtp.qq.com";

    // 服务器验证
    private static String KEY_PROPS = "mail.smtp.auth";
    private static String VALUE_PROPS = "true";
    // 发件人用户帐号、昵称和密码(邮箱必须开启SMTP服务才能使用)
    private static String SEND_USER = "1219964716@qq.com";
    private static String SEND_UNAME = "测试帐号";
    private static String SEND_PWD = "wb1234123";//邮箱独立密码





    /**
    * 创建session对象,此时需要传输协议,是否认证身份
    * @param protocol
    * @return
    */
    public Session createSession(String protocol){
        Properties propertie = new Properties();
        propertie.setProperty("mail.transport.protocol", protocol);
        //SMTP发送邮件,需要进行身份验证
        propertie.setProperty(KEY_PROPS, VALUE_PROPS);
        propertie.put(KEY_SMTP, VALUE_SMTP);

        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication(SEND_USER, SEND_PWD);
        }
        };
        //启动JavaMail调试功能,可以返回与SMTP服务交互的命令信息
        Session session = Session.getInstance(propertie,authenticator);
        session.setDebug(true);
        return session;
    }


    /**
    * 传入Session、MimeMessage对象,创建 Transport 对象发送邮件
    * @param session
    * @param msg
    * @throws Exception
    */
    public void sendMail(Session session, MimeMessage msg) throws Exception{
        // 由 Session 对象获得 Transport 对象
        Transport transport = session.getTransport();
        // 发送用户名、密码连接到指定的 smtp 服务器
        transport.connect(VALUE_SMTP, SEND_USER, SEND_PWD);

        // 设置邮件的收件人 TO:表示发件人    CC:表示抄送    BCC:表示暗送
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
        transport.close();
    }

    public static void main(String[] args) throws Exception {
        String receiveUser = "9653042143@qq.com";//收件人邮箱地址
        String headName = "创建内含附件、图文并茂的邮件!";
        String body = "<h4>内含附件、图文并茂的邮件测试!!!</h4> </br>" 
                        + "<a href = https://www.baidu.com/> 百度</a></br>" 
                        + "<img src = 'cid:logo_jpg'></a>"; 



        // MimeBodyPart attachment01 = WithAttachmentMessage.createAttachment("D:\\Java\\JS\\jquery2.1.3.js");
        // MimeBodyPart attachment02 = WithAttachmentMessage.createAttachment("D:\\Java\\JS\\jquery2.1.3.rar");
        MimeBodyPart content = WithAttachmentMessage.createContent(body, "E:\\logoMark.png");

        List<MimeBodyPart> bodyParts = new ArrayList<MimeBodyPart>();
        // bodyParts.add(attachment01);
        // bodyParts.add(attachment02);
        bodyParts.add(content);

        MessageSender sender = new MessageSender();
        Session session = sender.createSession("smtp");
        MimeMessage mail = new WithAttachmentMessage().createMessage(session, SEND_UNAME, SEND_USER, headName, receiveUser, bodyParts);
        sender.sendMail(session, mail);
    }

}

需要包:commons-lang-2.3.jar和mailapi.jar

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值