Latest web development tutorials

Java Invia Mail

Invia utilizzando applicazioni di posta elettronica Java è molto semplice, ma prima è necessario installare JavaMail API e Java Activation Framework (JAF) sulla vostra macchina.

  • È possibile scaricare l'ultima versione di Java del JavaMail , aprire la parte destra della pagina c'è un link Download, cliccaci sopra per scaricare.
  • È possibile scaricare l'ultima versione di Java (versione 1.1.1) JAF .

È inoltre possibile utilizzare il sito per fornire link per il download:

Scaricare e decomprimere il file nella directory di livello superiore appena creata, troverete alcuni file jar due applicazioni. È necessario aggiungere i filemail.jar e activation.jaral CLASSPATH.

Se si utilizza un server di posta di terze parti, come ad esempio del server SMTP QQ, è possibile visualizzare l'intero articolo in fondo dell'istanza autenticazione dell'utente.


Basta inviare una e-mail

Ecco un semplice esempio di invio di e-mail. Supponiamo che il vostro localhost già connesso alla rete.

// 文件名 SendEmail.java
 
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendEmail
{
   public static void main(String [] args)
   {   
      // 收件人电子邮箱
      String to = "[email protected]";
 
      // 发件人电子邮箱
      String from = "[email protected]";
 
      // 指定发送邮件的主机为 localhost
      String host = "localhost";
 
      // 获取系统属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认session对象
      Session session = Session.getDefaultInstance(properties);
 
      try{
         // 创建默认的 MimeMessage 对象
         MimeMessage message = new MimeMessage(session);
 
         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));
 
         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
 
         // Set Subject: 头部头字段
         message.setSubject("This is the Subject Line!");
 
         // 设置消息体
         message.setText("This is actual message");
 
         // 发送消息
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compilare ed eseguire il programma per inviare una semplice e-mail:

$ java SendEmail
Sent message successfully....

Se si desidera inviare una e-mail a più destinatari, utilizzare i seguenti metodi per specificare più destinatari ID:

void addRecipients(Message.RecipientType type,
                   Address[] addresses)
throws MessagingException

Quanto segue è la descrizione dei parametri:

  • Tipo: da impostare come A, CC o BCC CC qui per conto del CC, BCC rappresentanti di CC segreto y Esempio: .. Message.RecipientType.TO

  • indirizzi: Questo è l'ID di posta elettronica della matrice.Quando si specifica ID e-mail, è necessario utilizzare il metodo InternetAddress ().


Invia una e-mail HTML

Ecco un esempio di HTML e-mail inviata. Supponiamo che il vostro localhost già connesso alla rete.

Ed è molto simile a quella dell'esempio precedente, tranne che vogliamo usare il metodo setContent () per passare il secondo parametro è "text / html", per impostare il contenuto da inviare per specificare il contenuto HTML.

// 文件名 SendHTMLEmail.java
 
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendHTMLEmail
{
   public static void main(String [] args)
   {
     
      // 收件人电子邮箱
      String to = "[email protected]";
 
      // 发件人电子邮箱
      String from = "[email protected]";
 
      // 指定发送邮件的主机为 localhost
      String host = "localhost";
 
      // 获取系统属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象。
      Session session = Session.getDefaultInstance(properties);
 
      try{
         // 创建默认的 MimeMessage 对象。
         MimeMessage message = new MimeMessage(session);
 
         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));
 
         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
 
         // Set Subject: 头字段
         message.setSubject("This is the Subject Line!");
 
         // 发送 HTML 消息, 可以插入html标签
         message.setContent("<h1>This is actual message</h1>",
                            "text/html" );
 
         // 发送消息
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compilare ed eseguire questo programma per inviare e-mail HTML:

$ java SendHTMLEmail
Sent message successfully....

Invia e-mail con allegati

Ecco un esempio di e-mail con un allegato viene inviato. Supponiamo che il vostro localhost già connesso alla rete.

// 文件名 SendFileEmail.java
 
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendFileEmail
{
   public static void main(String [] args)
   {
     
      // 收件人电子邮箱
      String to = "[email protected]";
 
      // 发件人电子邮箱
      String from = "[email protected]";
 
      // 指定发送邮件的主机为 localhost
      String host = "localhost";
 
      // 获取系统属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象。
      Session session = Session.getDefaultInstance(properties);
 
      try{
         // 创建默认的 MimeMessage 对象。
         MimeMessage message = new MimeMessage(session);
 
         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));
 
         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));
 
         // Set Subject: 头字段
         message.setSubject("This is the Subject Line!");
 
         // 创建消息部分
         BodyPart messageBodyPart = new MimeBodyPart();
 
         // 消息
         messageBodyPart.setText("This is message body");
        
         // 创建多重消息
         Multipart multipart = new MimeMultipart();
 
         // 设置文本消息部分
         multipart.addBodyPart(messageBodyPart);
 
         // 附件部分
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);
 
         // 发送完整消息
         message.setContent(multipart );
 
         //   发送消息
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compilare ed eseguire il programma per inviare e-mail con allegati.

$ java SendFileEmail
Sent message successfully....

sezione Autenticazione utente

Se è necessario fornire un nome utente e una password per il server di posta elettronica per raggiungere lo scopo di autenticazione dell'utente, è possibile completare le seguenti impostazioni:

 props.put("mail.smtp.auth", "true");
 props.setProperty("mail.user", "myuser");
 props.setProperty("mail.password", "mypwd");

e-mail e altri meccanismi di attuazione coerenti con quanto sopra.

Si richiede una password nome utente messaggi di autenticazione inviati Esempio:

Nel server di posta ad esempio QQ presenti, per esempio, devi effettuare il login casella di posta QQ in background in "Impostazioni" = "conto aperto in servizio POP3 / SMTP, come illustrato di seguito:

qq-mail per impostare la password, generando una chiave di licenza:

codice Java è il seguente:

// 需要用户名密码邮件发送实例
//文件名 SendEmail2.java
//本实例以QQ邮箱为例,你需要在qq后台设置

import java.util.Properties;

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

public class SendEmail2
{
   public static void main(String [] args)
   {
      // 收件人电子邮箱
      String to = "[email protected]";

      // 发件人电子邮箱
      String from = "[email protected]";

      // 指定发送邮件的主机为 smtp.qq.com
      String host = "smtp.qq.com";  //QQ 邮件服务器

      // 获取系统属性
      Properties properties = System.getProperties();

      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);

      properties.put("mail.smtp.auth", "true");
      // 获取默认session对象
      Session session = Session.getDefaultInstance(properties,new Authenticator(){
	    public PasswordAuthentication getPasswordAuthentication()
	    {
	     return new PasswordAuthentication("[email protected]", "qq邮箱密码"); //发件人邮件用户名、密码
	    }
	   });

      try{
         // 创建默认的 MimeMessage 对象
         MimeMessage message = new MimeMessage(session);

         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));

         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: 头部头字段
         message.setSubject("This is the Subject Line!");

         // 设置消息体
         message.setText("This is actual message");

         // 发送消息
         Transport.send(message);
         System.out.println("Sent message successfully....from w3cschool.cc");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}