Jodd Email 发送邮件

Jodd版本:

    <dependency>
            <groupId>org.jodd</groupId>
            <artifactId>jodd-mail</artifactId>
            <version>3.7</version>
        </dependency>

发送一封简单的邮件:

package jodd.emial;

import java.io.File;
import java.io.IOException;

import jodd.io.FileUtil;
import jodd.mail.Email;
import jodd.mail.EmailAttachment;
import jodd.mail.EmailMessage;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpSslServer;
import jodd.mail.att.ByteArrayAttachment;
import jodd.mail.att.FileAttachment;
import jodd.util.MimeTypes;

public class JoddDemo {
    public static void main(String[] args) {
        try {
            sendEmail();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void sendEmail() throws IOException {
        // 创建邮件
        Email email = Email.create();
        // 设置邮件发送人
        email.from("su***g@qq.com");
        // 设置收件人
        email.to("64***76@qq.com");
        // 设置邮件主题
        email.subject("测试邮件");
        // 设置邮件内容,text格式
        @SuppressWarnings("unused")
        EmailMessage textMessage = new EmailMessage("Hello", MimeTypes.MIME_TEXT_PLAIN);
        // 设置邮件内容,html格式
        EmailMessage htmlMessage = new EmailMessage("<html><META http-equiv=Content-Type content=\"text/html; "
                + "charset=utf-8\"><body><h1>Hey!</h1><img src='cid:dongman1.jpg'>" + "<h2>Hay!</h2></body></html>",
                MimeTypes.MIME_TEXT_HTML);
        // 将邮件内容添加到邮件中
        email.addMessage(htmlMessage);

        // 创建字节数组附件
        EmailAttachment emailAttachment = new ByteArrayAttachment(
                FileUtil.readBytes(JoddDemo.class.getResource("/image/dongman1.jpg").getPath()), // 将图片读取存到字节数组中
                "image/jpg", // 附件文件类型
                "dongman1.jpg", // 附件名字
                "dongman1.jpg" );// 对应前面创建的cid名字,使用内联方式嵌入
        // 因为是内联方式,所以必须添加到内容中
        emailAttachment.setEmbeddedMessage(htmlMessage);

        EmailAttachment emailAttachment2 = new FileAttachment(
                new File(JoddDemo.class.getResource("/image/dongman2.jpg").getPath()), "dongman2.png", "dongman2.png");

        // 将附件添加到邮件中
        email.attach(emailAttachment);
        email.attach(emailAttachment2);

        // 发送邮件
        SmtpSslServer smtpServer = SmtpSslServer.create("smtp.exmail.qq.com").authenticateWith("sug***ng@qq.com",
                "Ad***55");
        // smtpServer.timeout(10);
        // smtpServer.properties(properties);
        SendMailSession session = smtpServer.createSession();
        session.open();
        session.sendMail(email);
        session.close();
    }

}

 

posted @ 2017-12-27 14:46  小蘇  阅读(908)  评论(0编辑  收藏  举报