Java - Envoi d'e-mails

Envoyer un e-mail à l'aide de votre application Java est assez simple mais pour commencer, vous devriez avoir JavaMail API et Java Activation Framework (JAF) installé sur votre machine.

Téléchargez et décompressez ces fichiers, dans les répertoires de niveau supérieur nouvellement créés, vous trouverez un certain nombre de fichiers jar pour les deux applications. Vous devez ajoutermail.jar et activation.jar fichiers dans votre CLASSPATH.

Envoyer un e-mail simple

Voici un exemple pour envoyer un simple e-mail depuis votre machine. On suppose que votrelocalhost est connecté à Internet et suffisamment capable d'envoyer un e-mail.

Exemple

// File Name SendEmail.java

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

public class SendEmail {

   public static void main(String [] args) {    
      // Recipient's email ID needs to be mentioned.
      String to = "[email protected]";

      // Sender's email ID needs to be mentioned
      String from = "[email protected]";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try {
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compilez et exécutez ce programme pour envoyer un simple e-mail -

Production

$ java SendEmail
Sent message successfully....

Si vous souhaitez envoyer un e-mail à plusieurs destinataires, les méthodes suivantes seront utilisées pour spécifier plusieurs ID e-mail -

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

Voici la description des paramètres -

  • type- Ce serait réglé sur TO, CC ou BCC. Ici, CC représente Carbon Copy et BCC représente Black Carbon Copy. Exemple: Message.RecipientType.TO

  • addresses- Ceci est un tableau d'ID de messagerie. Vous devrez utiliser la méthode InternetAddress () lors de la spécification des identifiants de messagerie.

Envoyer un e-mail HTML

Voici un exemple pour envoyer un e-mail HTML depuis votre machine. Ici, on suppose que votrelocalhost est connecté à Internet et suffisamment capable d'envoyer un e-mail.

Cet exemple est très similaire au précédent, sauf que nous utilisons ici la méthode setContent () pour définir le contenu dont le deuxième argument est "text / html" pour spécifier que le contenu HTML est inclus dans le message.

En utilisant cet exemple, vous pouvez envoyer un contenu HTML aussi volumineux que vous le souhaitez.

Exemple

// File Name SendHTMLEmail.java

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

public class SendHTMLEmail {

   public static void main(String [] args) {
      // Recipient's email ID needs to be mentioned.
      String to = "[email protected]";

      // Sender's email ID needs to be mentioned
      String from = "[email protected]";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try {
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Send the actual HTML message, as big as you like
         message.setContent("<h1>This is actual message</h1>", "text/html");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compilez et exécutez ce programme pour envoyer un e-mail HTML -

Production

$ java SendHTMLEmail
Sent message successfully....

Envoyer une pièce jointe par e-mail

Voici un exemple pour envoyer un e-mail avec pièce jointe depuis votre machine. Ici, on suppose que votrelocalhost est connecté à Internet et suffisamment capable d'envoyer un e-mail.

Exemple

// File Name SendFileEmail.java

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

public class SendFileEmail {

   public static void main(String [] args) {     
      // Recipient's email ID needs to be mentioned.
      String to = "[email protected]";

      // Sender's email ID needs to be mentioned
      String from = "[email protected]";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try {
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Create the message part 
         BodyPart messageBodyPart = new MimeBodyPart();

         // Fill the message
         messageBodyPart.setText("This is message body");
         
         // Create a multipar message
         Multipart multipart = new MimeMultipart();

         // Set text message part
         multipart.addBodyPart(messageBodyPart);

         // Part two is attachment
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);

         // Send the complete message parts
         message.setContent(multipart );

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compilez et exécutez ce programme pour envoyer un e-mail HTML -

Production

$ java SendFileEmail
Sent message successfully....

Partie authentification utilisateur

S'il est nécessaire de fournir un ID utilisateur et un mot de passe au serveur de messagerie à des fins d'authentification, vous pouvez définir ces propriétés comme suit:

props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");

Le reste du mécanisme d'envoi de courrier électronique resterait tel qu'expliqué ci-dessus.