[Java] JavaMail 发送 html 格式、带附件的邮件

本案例演示发送 html 格式,可带附件的邮件发送。发送纯文本邮件的例子可参照上一篇博文JavaMail 简单案例

EmailHelper, Email 的帮助类,向帮助类提供 SMTP 服务器域名、用户名、密码、发送人邮箱、收件人邮箱、邮件主题、html 格式的内容(可选)、附件(可选),便可发送一份邮件。

SendEmailDemo, 演示发送邮件。

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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailHelper {

    private String host;
    private String username;
    private String password;
    private String from;

    private String to;
    private String subject;
    private String htmlContent;
    private String attachedFileName;

    public EmailHelper(String host, String username, String password, String from) throws AddressException, MessagingException{
        this.host = host;
        this.username = username;
        this.password = password;
        this.from = from;
    }

    public void send() throws Exception{

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

        final String username1 = username;
        final String password1 = password;

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator(){
             protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication(username1, password1);
           }
        });        

        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));        

        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        message.setSubject(subject);

        Multipart multipart = new MimeMultipart();

        if (htmlContent != null){
            System.out.println(" has html ");

            BodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(htmlContent, "text/html");
            multipart.addBodyPart(htmlPart);
        }

        if (attachedFileName != null){
            System.out.println(" has attached file ");

            BodyPart attchmentPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachedFileName);
            attchmentPart.setDataHandler(new DataHandler(source));
            attchmentPart.setFileName(attachedFileName);
            multipart.addBodyPart(attchmentPart);
        }

        message.setContent(multipart);
        Transport.send(message);

        System.out.println(" Sent ");
    }

    public void setTo(String to) {
        this.to = to;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setHtmlContent(String htmlContent) {
        this.htmlContent = htmlContent;
    }

    public void setAttachedFileName(String attachedFileName) {
        this.attachedFileName = attachedFileName;
    }
}

演示代码,

public class SendEmailDemo {

    public static void main(){

        String host = "smtp.163.com";        // use your smtp server host

        final String username = "[email protected]"; // use your username
        final String password = "password";   // use your password

        String from = "[email protected]";     // use your sender email address

        String to = "[email protected]";  // use your reciever email address
        try {
            EmailHelper emailHelper = new EmailHelper(host, username, password, from);
            emailHelper.setTo(to);
            emailHelper.setSubject("subject ttt test");
            emailHelper.setHtmlContent("<h1> This is html </h1>");
            emailHelper.setAttachedFileName("/Users/grs/Documents/Java/mavenEmail/test/src/main/resource/attachment3.txt");

            emailHelper.send();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

参考资料

Java - Sending Email

时间: 2024-10-05 23:09:14

[Java] JavaMail 发送 html 格式、带附件的邮件的相关文章

python+selenium实现发送一封带附件的邮件

163邮件登录首页 登录成功断言是否有退出按钮 点击退出退出登录 from selenium import webdriver import unittest import time class VisitSogouByChrome(unittest.TestCase): def setUp(self): # 启动Chrome浏览器 self.driver = webdriver.Chrome(executable_path = "e:\\chromedriver.exe") def

[Java] JavaMail 发送带图片的 html 格式的邮件

JavaMail 发送的邮件正文和附件是相互独立的,但是内置图片需要定位图片在正文中的位置,所以内置图片和邮件正文是互相依赖的. 发送带附件的邮件可参考JavaMail 发送 html 格式.带附件的邮件. 发送纯文本的邮件可参照 JavaMail 简单案例. 具体例子 EmailHelper, Email 的帮助类,向帮助类提供 SMTP 服务器域名.用户名.密码.发送人邮箱.收件人邮箱.邮件主题.html 格式的内容.图片的路径,便可发送一份内置图片的邮件.在创建 MimeMultipart

(转)用javamail发送带附件的邮件

本文转载自:http://redleaf.iteye.com/blog/78217 mail.java 代码 package mail; import java.util.* ; import java.io.* ; import javax.mail.* ; import javax.mail.internet.* ; import javax.activation.* ; public class Mail { //定义发件人.收件人.SMTP服务器.用户名.密码.主题.内容等 privat

Android上发送带附件的邮件

准备工作-下载最新版本的JMail https://java.net/projects/javamail/pages/Home#Download_JavaMail_1.5.2_Release http://www.oracle.com/technetwork/java/javase/downloads/index-135046.html 在android上发送邮件方式: 第一种:借助GMail APP客户端,缺点是必须使用GMail帐号,有点是比较方便 不需要写很多代码,但是不是很灵活. 第二种

java代码如何发送一封带图片的邮件

本章记录三个,1.java 发送普通的邮件  2.java发送带附件的邮件 3.java发送带图片的邮件 1.java发送普通邮件--首先要设置如下的几个具体的参数: public static String username = "***@163.com"; // 服务邮箱(from邮箱)public static String password = "*****"; // 邮箱密码public static String senderNick = "*

自动化测试发送带附件的邮件

自动化测试发送带附件的邮件 标签(空格分隔): 带附件邮件 在我们的自动化测试中,有时候会发送报告,有时候会发送带附件的报告,具体带附件的报告怎么操作呢? 具体的步骤如下述所示:如下是QQ邮箱为例 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # 用于传送附件 smtpserver = 'smtp.exmail.qq.com' user = '*

C#发送带附件的邮件的代码

如下的代码是关于C#发送带附件的邮件的代码. MailMessage m = new MailMessage();m.Subject = "File attachment!";m.Body = "See the attached file.";m.Attachments.Add(new Attachment(@"C:test.txt"));SmtpClient client = new SmtpClient("smtp.w3mentor

【Mail】JavaMail发送带附件的邮件

上一篇讲了使用JavaMail发送普通邮件([Mail]JavaMail介绍及发送邮件(一)),本例讲发送复杂的邮件(带有附件的邮件) 生成一封复杂的邮件 新建一个JavaWeb的Maven工程,引入javamail.jar包,maven引用如下: 1 <!-- javamail --> 2 <dependency> 3 <groupId>javax.mail</groupId> 4 <artifactId>mail</artifactId

Apache Mail 发送带附件的邮件

MultiPartEmail email = new MultiPartEmail(); email.setDebug(true); email.setHostName("smtp.sina.com"); email.setAuthentication("发送邮件帐号", "邮箱登录密码"); email.setCharset("UTF-8"); try { email.setFrom("发送邮件帐号",