JavaMail详解(三)——发送邮件 - 高飞网
250 人阅读

JavaMail详解(三)——发送邮件

2017-07-28 02:09:46

    现在我们已经对JavaMail API和核心类都有了初步的了解,现在来写一个简单的程序发送简单的邮件、带附件的邮件、HTML内容的邮件和内嵌图片的邮件。

    上面所有场景都有下面的相同的基本步骤:

  1. 获得Session对象
  2. 组装消息
  3. 发送消息

发送简单邮件

    SendEmail.java

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {
    public static void main(String[] args) {
        // 指定接收者
        String to = "xxxxxxx@163.com";

        // 指定发送者
        String from = "support_test@163.com";
        final String username = "support_test@163.com";
        final String password = "xxxxxxx";

        //发送服务器主机
        String host = "smtp.163.com";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "25");

        //得到session对象
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            //创建默认的MimeMessage对象
            Message message = new MimeMessage(session);

            //设置消息头字段From
            message.setFrom(new InternetAddress(from));

            //设置消息头字段To
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

            //设置消息头字段:邮件标题
            message.setSubject("测试邮件");

            //发送的文本内容
            message.setText("嗨,这是用JavaMailAPI发送的测试邮件");

            //发送
            Transport.send(message);

            System.out.println("发送成功....");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

结果:



发送带附件邮件

SendAttachmentInEmail.java

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.PasswordAuthentication;
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;

public class SendAttachmentInEmail {
    public static void main(String[] args) {
        // 指定收信人
        String to = "xxxxxx@163.com";

        // 指定发信人
        String from = "support_test@163.com";

        final String username = "support_test@163.com";
        final String password = "xxxxx";

        // 指定发信服务器主机
        String host = "smtp.163.com";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "25");

        // 获得Session对象
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 创建默认的MimeMessage对象
            Message message = new MimeMessage(session);

            // 设置消息头字段From
            message.setFrom(new InternetAddress(from));

            // 设置消息头字段To
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

            // 设置消息头字段:邮件标题
            message.setSubject("测试邮件-带附件");

            // 创建消息片段
            BodyPart messageBodyPart = new MimeBodyPart();
            // 文本部分
            messageBodyPart.setText("这是消息体");

            // 创建复合消息
            Multipart multipart = new MimeMultipart();

            // 设置文本消息
            multipart.addBodyPart(messageBodyPart);

            // 消息第二部分是附件
            messageBodyPart = new MimeBodyPart();
            String filename = "c:/abc.txt";
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);

            // 设置完整消息
            message.setContent(multipart);

            // 发送消息
            Transport.send(message);

            System.out.println("发消息成功....");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

结果:

特别提醒,在发送含有附件内容的邮件时,如果文件名为中文,可能会导致发送的邮件中,附件会丢失,为解决该问题,应该将文件名转一下码:

MimeUtility.encodeText(filename)

笔者曾因该问题困扰了好久.

发送HTML内容邮件


import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendHTMLEmail {
    public static void main(String[] args) {
        // 指定收信人
        String to = "xxxxxx@163.com";

        // 指定发信人
        String from = "support_test@163.com";

        final String username = "support_test@163.com";
        final String password = "xxxxx";

        // 指定发信服务器主机
        String host = "smtp.163.com";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "25");

        // 获得Session对象
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 创建默认的MimeMessage对象
            Message message = new MimeMessage(session);

            // 设置消息头字段From
            message.setFrom(new InternetAddress(from));

            // 设置消息头字段To
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

            // 设置消息头字段:邮件标题
            message.setSubject("HTML测试邮件");

            // 发送HTML格式邮件
            message.setContent("<h1>This is actual message embedded in HTML tags</h1>", "text/html");

            // 发送
            Transport.send(message);

            System.out.println("发送成功....");
        } catch (MessagingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

结果:



发送内嵌图片的邮件


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.PasswordAuthentication;
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;

public class SendInlineImagesInEmail {
    public static void main(String[] args) {
        // 指定接收者
        String to = "xxxxxxxx@163.com";

        // 指定发送者
        String from = "support_test@163.com";
        final String username = "support_test@163.com";
        final String password = "xxxxx";

        // 发送服务器主机
        String host = "smtp.163.com";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "25");

        // 得到session对象
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        try {

            // 创建默认的MimeMessage对象
            Message message = new MimeMessage(session);

            // 设置消息头字段From
            message.setFrom(new InternetAddress(from));

            // 设置消息头字段To
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

            // 设置消息头字段:邮件标题
            message.setSubject("内嵌图片的邮件");

            //该邮件有两部分,BODY和嵌入图片部分
            MimeMultipart multipart = new MimeMultipart("related");

            //第一部分HTML代码
            BodyPart messageBodyPart = new MimeBodyPart();
            String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
            messageBodyPart.setContent(htmlText, "text/html");
            // add it
            multipart.addBodyPart(messageBodyPart);

            // 第二部分 (图片)
            messageBodyPart = new MimeBodyPart();
            DataSource fds = new FileDataSource("c:/redhat.jpg");

            messageBodyPart.setDataHandler(new DataHandler(fds));
            messageBodyPart.setHeader("Content-ID", "<image>");

            // add image to the multipart
            multipart.addBodyPart(messageBodyPart);

            // put everything together
            message.setContent(multipart);
            // 发送
            Transport.send(message);

            System.out.println("发送成功....");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}


结果:




还没有评论!
54.81.157.56