java 郵件發送與帶附件的實現方法

來源:互聯網
上載者:User

java 郵件發送與帶附件的實現方法
java郵件發送也一樣,可以實現傳入的參數有port地址、密碼、姓名、誰發、發給誰、主題、本文內容、smtp地址、發送類型
等功能。
方法一

簡單的JavaMail郵件發送
dev.firnow.com    時間 : 2009-04-05  作者:匿名   編輯:sky 點擊:  683 [ 評論 ]
-
-

 

import javax.mail.*;
import java.util.*;
import javax.mail.internet.*;

 

/**
 * @author caoyx
 *
 */
public class MailTest {

 /**
  * 構造方法
  */
 public MailTest() {

 }

/**

*

*javamail發送測試

*/

  public void SendEmailTest() {


  Properties props教程 = new Properties();
  props.put("mail.smtp.host", "smtp.163.com");
 
  // 允許smtp校正
  props.put("mail.smtp.auth", "true");
  Session sendMailSession = Session.getInstance(props, null);

  try {
   Transport transport = sendMailSession.getTransport("smtp");
  
   //                             郵箱伺服器            登陸信箱使用者名     登陸密碼
   transport.connect("smtp.163.com",   "xxx",                 "xxx");
   Message newMessage = new MimeMessage(sendMailSession);

   // 設定mail主題
   String mail_subject = "郵件發送測試(mail標題)";
   newMessage.setSubject(mail_subject);

   // 設定發信人地址
   String strFrom = "xiangzi551@163.com";
   strFrom = new String(strFrom.getBytes(), "8859_1");
   newMessage.setFrom(new InternetAddress(strFrom));
   Address addressFrom[] = {
     new InternetAddress("xiangzi551@163.com"),
     new InternetAddress("xiangzi551@163.c dfgdom") };
  
   // 改變寄件者地址
   newMessage.addFrom(addressFrom);
  
   // 設定收件者地址
   Address addressTo[] = { new InternetAddress("cyx_shzu@163.com") };
   newMessage.setRecipients(Message.RecipientType.TO, addressTo);

   // 設定mail本文
   newMessage.setSentDate(new java.util.Date());
  
   String mail_text = "郵件發送測試.來自: "+strFrom;
   newMessage.setText(mail_text);

   // 儲存發送資訊
   newMessage.saveChanges();
  
   // 發送郵件
   transport.sendMessage(newMessage, newMessage
     .getRecipients(Message.RecipientType.TO));

   transport.close();

 

   System.out.println("OK");
  } catch (Exception e) {
   System.out.println(e);
  }

 }

 public static void main(String args[]) throws Exception {
  MailTest SEmail = new MailTest();
  SEmail.SendEmailTest();
 }

}

 

測試:

在eclipse中建立一個Java Application

引入mail.jar    activation.jar

執行個體二

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;

public class MainClass {

  public static void main(String[] args) throws Exception {
    URLName server = new URLName("protocol://username@host/foldername");

    Session session = Session.getDefaultInstance(new Properties(), new MailAuthenticator());

    Folder folder = session.getFolder(server);
    if (folder == null) {
      System.out.println("Folder " + server.getFile() + " not found.");
      System.exit(1);
    }
    folder.open(Folder.READ_ONLY);

    Message[] messages = folder.getMessages();
    for (int i = 0; i < messages.length; i++) {
      System.out.println(messages[i].getSize() + " bytes long.");
      System.out.println(messages[i].getLineCount() + " lines.");
      String disposition = messages[i].getDisposition();
      if (disposition == null){
        ; // do nothing
      }else if (disposition.equals(Part.INLINE)) {
        System.out.println("This part should be displayed inline");
      } else if (disposition.equals(Part.ATTACHMENT)) {
        System.out.println("This part is an attachment");
        String fileName = messages[i].getFileName();
        System.out.println("The file name of this attachment is " + fileName);
      }
      String description = messages[i].getDescription();
      if (description != null) {
        System.out.println("The description of this message is " + description);
      }
    }
    folder.close(false);
  }
}

class MailAuthenticator extends Authenticator {

  public MailAuthenticator() {
  }

  public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("username", "password");
  }
}

如何使用FileDataSource通過郵件發送一個檔案

 

import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class sendfile {

    public static void main(String[] args) {
  if (args.length != 5) {
      System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
      System.exit(1);
  }

  String to = args[0];
  String from = args[1];
  String host = args[2];
  String filename = args[3];
  boolean debug = Boolean.valueOf(args[4]).booleanValue();
  String msgText1 = "Sending a file.n";
  String subject = "Sending a file";
 
  // create some properties and get the default Session
  Properties props = System.getProperties();
  props.put("mail.smtp.host", host);
 
  Session session = Session.getInstance(props, null);
  session.setDebug(debug);
 
  try {
      // create a message
      MimeMessage msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(from));
      InternetAddress[] address = {new InternetAddress(to)};
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject(subject);

      // create and fill the first message part
      MimeBodyPart mbp1 = new MimeBodyPart();
      mbp1.setText(msgText1);

      // create the second message part
      MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
        FileDataSource fds = new FileDataSource(filename);
      mbp2.setDataHandler(new DataHandler(fds));
      mbp2.setFileName(fds.getName());

      // create the Multipart and add its parts to it
      Multipart mp = new MimeMultipart();
      mp.addBodyPart(mbp1);
      mp.addBodyPart(mbp2);

      // add the Multipart to the message
      msg.setContent(mp);

      // set the Date: header
      msg.setSentDate(new Date());
     
      // send the message
      Transport.send(msg);
     
  } catch (MessagingException mex) {
      mex.printStackTrace();
      Exception ex = null;
      if ((ex = mex.getNextException()) != null) {
    ex.printStackTrace();
      }
  }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.