[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 = "sender@163.com"; // use your username
        final String password = "password";   // use your password

        String from = "sender@163.com";     // use your sender email address

        String to = "reciever@foxmail.com";  // 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();
        }
    }
}

 

需要读取邮箱邮件,可参考另一篇博文 JavaMail 查询邮件

 

参考资料

Java - Sending Email

 

posted @ 2016-06-17 01:30  TonyYPZhang  阅读(7680)  评论(0编辑  收藏  举报