集册 Java实例教程 通过MimeMessage发送邮件

通过MimeMessage发送邮件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

570
通过MimeMessage发送邮件


//package com.nowjava;/*来自 时代Java - nowjava.com*/

import java.io.File;

import java.io.UnsupportedEncodingException;


import javax.activation.DataHandler;

import javax.activation.FileDataSource;


import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

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;

import javax.mail.internet.MimeUtility;//n  o  w  j  a  v  a . c o m 提 供


public class Main {


    private static void sendMail(String subject, String content,

            String toEmail, String fromEmail, String fromName,

            String charset, File[] attachFiles, Session session)

            throws UnsupportedEncodingException, MessagingException {

        MimeMessage message = new MimeMessage(session);

        InternetAddress addr = new InternetAddress(fromEmail, fromName,

                charset);

        message.setFrom(addr);

        message.setSubject(subject);

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(

                toEmail));


        if (attachFiles == null) {

            message.setContent(content, "text/html; charset=" + charset);

        } else {

            Multipart multipart = new MimeMultipart();

            BodyPart messageBodyPart = new MimeBodyPart();


            messageBodyPart.setText(content);

            multipart.addBodyPart(messageBodyPart);


            for (File f : attachFiles) {

                BodyPart fileBodyPart = new MimeBodyPart();

                FileDataSource
展开阅读全文