java mail實現Email的發送,完整代碼


java mail實現Email的發送,完整代碼

 

1、對應用程序配置郵件會話

 首先, 導入jar

    <dependencies>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.5.2</version>
        </dependency>
    </dependencies>

 

  javax.mail.Session保存郵件系統的配置屬性和提供用戶驗證的信息,發送email首先要獲取session對象。

    1.  Session.getInstance(java.util.Properties)獲取非共享的session對象
    2.  Session.getDefaultInstance(java.utilProperties)獲取共享的session對象

  兩者都必須建立Properties prop=new Properties()對象;

 

注意:  一般對單用戶桌面應用程序使用共享Session對象。

 

  用SMTP協議發送Email時通常要設置mail.smtp.host(mail.protocol.host協議特定郵件服務器名)屬性。

prop.put("mail.smtp.host","smtp.mailServer.com");

Session mailSession=Session.getInstance(prop);

 

注意:  在真正使用創建的過程中,往往會讓我們驗證密碼,這是我們要寫一個密碼驗證類。javax.mail.Authenticator是一個抽象類,我們要寫MyAuthenticator的密碼驗證類,該類繼承Authenticator實現:

 protected PasswordAuthentication getPasswordAuthentication(){   
      return new PasswordAuthentication(String userName, String password);   
  }

這時我們創建Session對象:

Session mailSession=Session.getInstance(prop,new MyAuthenticator(userName,Password));

prop.put("mail.smtp.auth","true"); //並且要設置使用驗證:
prop.put("mail.smtp.starttls.enable","true"); //使用 STARTTLS安全連接:

 

 

 

2、配置郵件會話之后,要編寫消息

  要編寫消息就要生成javax.mail.Message子類的實例或對Internet郵件使用javax.mail.interet.MimeMessage類。

 

(1)建立MimeMessage對象

  MimeMessage擴展抽象的Message類,構造MimeMessage對象:

MimeMessage message=new MimeMessage(mailSession);

 

 

(2)消息發送者、日期、主題 

message.setFrom(Address theSender);
message.setSentDate(java.util.Date theDate);
message.setSubject(String theSubject);

 

(3)設置消息的接受者與發送者(尋址接收)

  setRecipient(Message.RecipientType type , Address theAddress)、setRecipients(Message.RecipientType type , Address[] theAddress)、addRecipient(Message.RecipientType type , Address theAddress)、addRecipients(Message.RecipientType type,Address[] theAddress)方法都可以指定接受者類型,但是一般用后兩個,這樣可以避免意外的替換或者覆蓋接受者名單。定義接受者類型:

Message.RecipientType.TO://消息接受者
Message.RecipientType.CC://消息抄送者
Message.RecipientType.BCC://匿名抄送接收者(其他接受者看不到這個接受者的姓名和地址)

 

(4)設置消息內容

  JavaMail基於JavaBean Activation FrameWork(JAF),JAF可以構造文本消息也可以支持附件。

  設置消息內容時,要提供消息的內容類型-----即方法簽名:

MimeMessage.setContent(Object theContent,String type);

也可以不用顯式的制定消息的內容類型:MimeMessage.setText(String theText);

注意:建立地址javax.mail.InternetAddress toAddress=new InternetAddress(String address);

 

3、發送Email,這里以文本消息為例

  javax.mail.Transport類來發送消息。這時Transport對象與相應傳輸協議通信,這里是SMTP協議。

Transport transport = mailSession.getTransport("smtp");//定義發送協議
transport.connect(smtpHost,"chaofeng19861126", fromUserPassword);//登錄郵箱
transport.send(message, message.getRecipients(RecipientType.TO));//發送郵件

下面是一個完整的代碼:--------->>SendMail.java

 

package com.tools;

import java.util.Calendar;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {
    @SuppressWarnings("static-access")
    public static void sendMessage(String smtpHost, String from,
            String fromUserPassword, String to, String subject,
            String messageText, String messageType) throws MessagingException {
        // 第一步:配置javax.mail.Session對象
        System.out.println("為" + smtpHost + "配置mail session對象");

        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.starttls.enable", "true");// 使用 STARTTLS安全連接
        // props.put("mail.smtp.port", "25"); //google使用465或587端口
        props.put("mail.smtp.auth", "true"); // 使用驗證
        // props.put("mail.debug", "true");
        Session mailSession = Session.getInstance(props, new MyAuthenticator(
                from, fromUserPassword));

        // 第二步:編寫消息
        System.out.println("編寫消息from——to:" + from + "——" + to);

        InternetAddress fromAddress = new InternetAddress(from);
        InternetAddress toAddress = new InternetAddress(to);

        MimeMessage message = new MimeMessage(mailSession);

        message.setFrom(fromAddress);
        message.addRecipient(RecipientType.TO, toAddress);

        message.setSentDate(Calendar.getInstance().getTime());
        message.setSubject(subject);
        message.setContent(messageText, messageType);

        // 第三步:發送消息
        Transport transport = mailSession.getTransport("smtp");
        transport.connect(smtpHost, "chaofeng19861126", fromUserPassword);
        transport.send(message, message.getRecipients(RecipientType.TO));
        System.out.println("message yes");
    }

    public static void main(String[] args) {
        try {
            SendMail.sendMessage("smtp.gmail.com", "karemjohn@gmail.com",
                    "************", "karemjohn@gmail.com", "nihao",
                    "---------------wrwe-----------",
                    "text/html;charset=gb2312");
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class MyAuthenticator extends Authenticator {
    String userName = "";
    String password = "";

    public MyAuthenticator() {

    }

    public MyAuthenticator(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password);
    }
}

 

前邊發過一個比較簡單,這個就比較適用了,也方便以后使用:

第一個文件:------>>MailSenderInfo.java

功能:封裝了發送郵件的基本信息

package com.util.mail;  
/**  
* 發送郵件需要使用的基本信息  
*/   
import java.util.Properties;   
public class MailSenderInfo {   
      
    // 發送郵件的服務器的IP和端口   
    private String mailServerHost;   
    private String mailServerPort = "25";   
      
    // 郵件發送者的地址   
    private String fromAddress;   
      
    // 郵件接收者的地址   
    private String toAddress;   
      
    // 登陸郵件發送服務器的用戶名和密碼   
    private String userName;   
    private String password;   
      
    // 是否需要身份驗證   
    private boolean validate = false;   
      
    // 郵件主題   
    private String subject;   
      
    // 郵件的文本內容   
    private String content;   
      
    // 郵件附件的文件名   
    private String[] attachFileNames;     
    /**  
      * 獲得郵件會話屬性  
      */   
    public Properties getProperties(){   
      Properties p = new Properties();   
      p.put("mail.smtp.host", this.mailServerHost);   
      p.put("mail.smtp.port", this.mailServerPort);   
      p.put("mail.smtp.auth", validate ? "true" : "false");   
      return p;   
    }   
    public String getMailServerHost() {   
      return mailServerHost;   
    }   
    public void setMailServerHost(String mailServerHost) {   
      this.mailServerHost = mailServerHost;   
    }  
    public String getMailServerPort() {   
      return mailServerPort;   
    }  
    public void setMailServerPort(String mailServerPort) {   
      this.mailServerPort = mailServerPort;   
    }  
    public boolean isValidate() {   
      return validate;   
    }  
    public void setValidate(boolean validate) {   
      this.validate = validate;   
    }  
    public String[] getAttachFileNames() {   
      return attachFileNames;   
    }  
    public void setAttachFileNames(String[] fileNames) {   
      this.attachFileNames = fileNames;   
    }  
    public String getFromAddress() {   
      return fromAddress;   
    }   
    public void setFromAddress(String fromAddress) {   
      this.fromAddress = fromAddress;   
    }  
    public String getPassword() {   
      return password;   
    }  
    public void setPassword(String password) {   
      this.password = password;   
    }  
    public String getToAddress() {   
      return toAddress;   
    }   
    public void setToAddress(String toAddress) {   
      this.toAddress = toAddress;   
    }   
    public String getUserName() {   
      return userName;   
    }  
    public void setUserName(String userName) {   
      this.userName = userName;   
    }  
    public String getSubject() {   
      return subject;   
    }  
    public void setSubject(String subject) {   
      this.subject = subject;   
    }  
    public String getContent() {   
      return content;   
    }  
    public void setContent(String textContent) {   
      this.content = textContent;   
    }   
}   

第二個文件:----------->>SimpleMailSender.java

功能:一個只發送文本的發送器

package com.util.mail;  
  
import java.util.Date;   
import java.util.Properties;  
import javax.mail.Address;   
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;   
  
/**  
* 簡單郵件(不帶附件的郵件)發送器  
*/   
public class SimpleMailSender  {   
/**  
  * 以文本格式發送郵件  
  * @param mailInfo 待發送的郵件的信息  
  */   
    public boolean sendTextMail(MailSenderInfo mailInfo) {   
      // 判斷是否需要身份認證   
      MyAuthenticator authenticator = null;   
      Properties pro = mailInfo.getProperties();  
      if (mailInfo.isValidate()) {   
      // 如果需要身份認證,則創建一個密碼驗證器   
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());   
      }  
      // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session   
      Session sendMailSession = Session.getDefaultInstance(pro,authenticator);   
      try {   
      // 根據session創建一個郵件消息   
      Message mailMessage = new MimeMessage(sendMailSession);   
      // 創建郵件發送者地址   
      Address from = new InternetAddress(mailInfo.getFromAddress());   
      // 設置郵件消息的發送者   
      mailMessage.setFrom(from);   
      // 創建郵件的接收者地址,並設置到郵件消息中   
      Address to = new InternetAddress(mailInfo.getToAddress());   
      mailMessage.setRecipient(Message.RecipientType.TO,to);   
      // 設置郵件消息的主題   
      mailMessage.setSubject(mailInfo.getSubject());   
      // 設置郵件消息發送的時間   
      mailMessage.setSentDate(new Date());   
      // 設置郵件消息的主要內容   
      String mailContent = mailInfo.getContent();   
      mailMessage.setText(mailContent);   
      // 發送郵件   
      Transport.send(mailMessage);  
      return true;   
      } catch (MessagingException ex) {   
          ex.printStackTrace();   
      }   
      return false;   
    }   
      
    /**  
      * 以HTML格式發送郵件  
      * @param mailInfo 待發送的郵件信息  
      */   
    public static boolean sendHtmlMail(MailSenderInfo mailInfo){   
      // 判斷是否需要身份認證   
      MyAuthenticator authenticator = null;  
      Properties pro = mailInfo.getProperties();  
      //如果需要身份認證,則創建一個密碼驗證器    
      if (mailInfo.isValidate()) {   
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());  
      }   
      // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session   
      Session sendMailSession = Session.getDefaultInstance(pro,authenticator);   
      try {   
      // 根據session創建一個郵件消息   
      Message mailMessage = new MimeMessage(sendMailSession);   
      // 創建郵件發送者地址   
      Address from = new InternetAddress(mailInfo.getFromAddress());   
      // 設置郵件消息的發送者   
      mailMessage.setFrom(from);   
      // 創建郵件的接收者地址,並設置到郵件消息中   
      Address to = new InternetAddress(mailInfo.getToAddress());   
      // Message.RecipientType.TO屬性表示接收者的類型為TO   
      mailMessage.setRecipient(Message.RecipientType.TO,to);   
      // 設置郵件消息的主題   
      mailMessage.setSubject(mailInfo.getSubject());   
      // 設置郵件消息發送的時間   
      mailMessage.setSentDate(new Date());   
      // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象   
      Multipart mainPart = new MimeMultipart();   
      // 創建一個包含HTML內容的MimeBodyPart   
      BodyPart html = new MimeBodyPart();   
      // 設置HTML內容   
      html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");   
      mainPart.addBodyPart(html);   
      // 將MiniMultipart對象設置為郵件內容   
      mailMessage.setContent(mainPart);   
      // 發送郵件   
      Transport.send(mailMessage);   
      return true;   
      } catch (MessagingException ex) {   
          ex.printStackTrace();   
      }   
      return false;   
    }   
}   

第三個文件:——————>>MyAuthenticator.java

功能:密碼驗證器

package com.util.mail;  
  
import javax.mail.*;  
  /** 
     密碼驗證器 
  */  
public class MyAuthenticator extends Authenticator{  
    String userName=null;  
    String password=null;  
       
    public MyAuthenticator(){  
    }  
    public MyAuthenticator(String username, String password) {   
        this.userName = username;   
        this.password = password;   
    }   
    protected PasswordAuthentication getPasswordAuthentication(){  
        return new PasswordAuthentication(userName, password);  
    }  
}  
   

 

程序入口,主函數:

public static void main(String[] args){  
        //這個類主要是設置郵件  
      MailSenderInfo mailInfo = new MailSenderInfo();   
      mailInfo.setMailServerHost("smtp.163.com");   
      mailInfo.setMailServerPort("25");   
      mailInfo.setValidate(true);   
      mailInfo.setUserName("chaofeng19861126@163.com");   
      mailInfo.setPassword("********");//您的郵箱密碼   
      mailInfo.setFromAddress("chaofeng19861126@163.com");   
      mailInfo.setToAddress("karemjohn@gmail.com");   
      mailInfo.setSubject("設置郵箱標題");   
      mailInfo.setContent("設置郵箱內容");   
        //這個類主要來發送郵件  
      SimpleMailSender sms = new SimpleMailSender();  
         sms.sendTextMail(mailInfo);//發送文體格式   
         sms.sendHtmlMail(mailInfo);//發送html格式  
    }  

 

 

 

 

 

出自:  http://blog.csdn.net/karem/article/details/4646071

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM