集册 Java实例教程 使用MimeMultipart发送电子邮件

使用MimeMultipart发送电子邮件

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

459
使用MimeMultipart发送电子邮件
/**
时 代 J a v a 公 众 号 - nowjava.com 提供 
**/


import java.util.Date;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

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;


public class sendfile {

  String from = "asdf@gmail.com";

  String to = null;

  String d_host = "smtp.gmail.com";

  String d_port = "465";
  /** 
  来 自 
  N o  w  J a v a . c o m - 时  代  Java
  **/

  String subject = "Important Message";

  String bodyText = null;

  String filename = null;


  public static void main(String[] args) {


  }


  public sendfile(String m1_to, String m1_text, String fl) {


    to = m1_to;

    bodyText = m1_text;

    filename = fl;

  }


  public void sendEmail() {


    Properties properties = new Properties();

    properties.put("mail.smtp.host", "smtp.gmail.com");

    properties.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(properties, null);


    try {

      MimeMessage message = new MimeMessage(session);

      message.setFrom(new InternetAddress(from));

      message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

      message.setSubject(subject);

      message.setSentDate(new Date());


      //

      // Set the email message text.

      //

      MimeBodyPart messagePart = new MimeBodyPart();

      messagePart.setText(bodyText);


      //

      // Set the email attachment file

      //

      MimeBodyPart attachmentPart = new MimeBodyPart();

      FileDataSource fileDataSource = new FileDataSource(filename) {

        @Override

        public String getContentType() {

          
展开阅读全文