JavaMail

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * Created by YuWenHui on 2017/4/20 0020.
 */

public class Demo {
    @org.junit.Test
    public void fun1() throws Exception {
//        获得session
        Properties properties = new Properties();
        properties.setProperty("mail.host","smtp.qq.com");
        properties.setProperty("mail.smtp.auth","true");

        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
//密码和账号,这里的账号不能加@qq.com
return new PasswordAuthentication("xxx","xxx"); } }; Session session = Session.getInstance(properties,auth); // 创建MimeMessage MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("xxx@qq.com"));//设置发件人 message.setRecipients(MimeMessage.RecipientType.TO,"xxx@qq.com");//设置收件人 message.setSubject("这是Javamail的测试邮件"); message.setContent("看玩就删","text/html;charset=utf-8"); // 发送 Transport.send(message); } }

添加附件模块

 /*
         * 当发送包含附件的邮件时,邮件体就为多部件形式!
         * 1. 创建一个多部件的部件内容!MimeMultipart
         *   MimeMultipart就是一个集合,用来装载多个主体部件!
         * 2. 我们需要创建两个主体部件,一个是文本内容的,另一个是附件的。
         *   主体部件叫MimeBodyPart
         * 3. 把MimeMultipart设置给MimeMessage的内容!
         */
        MimeMultipart list = new MimeMultipart();//创建多部分内容

        // 创建MimeBodyPart
        MimeBodyPart part1 = new MimeBodyPart();
        // 设置主体部件的内容
        part1.setContent("这是一封包含附件的垃圾邮件", "text/html;charset=utf-8");
        // 把主体部件添加到集合中
        list.addBodyPart(part1);


        // 创建MimeBodyPart
        MimeBodyPart part2 = new MimeBodyPart();
        part2.attachFile(new File("F:xxx.jpg"));//设置附件的内容
        part2.setFileName(MimeUtility.encodeText("xxx.jpg"));//设置显示的文件名称,其中encodeText用来处理中文乱码问题
        list.addBodyPart(part2);

        message.setContent(list);//把它设置给邮件作为邮件的内容。

利用jar包来进行

    (F:\常用综合\常用jar包\JavaMail\itcast-tools-1.4.2.jar)

 @Test
    public  void  fun2() throws Exception{
        Session session = MailUtils.createSession("smtp.qq.com","1623851096","yu1623851096");
        Mail mail = new Mail("1623851096@qq.com","987039024@qq.com","这是经过包装的测试文件","余文辉是大帅哥");
        AttachBean attachBean = new AttachBean(new File("D:/Pictures/doubi.jpg"),"逗比.jpg");
        mail.addAttach(attachBean);
        MailUtils.send(session,mail);
    }

 

posted @ 2017-04-20 11:49  西瓜的小弟西西瓜  阅读(209)  评论(0编辑  收藏  举报