Fabrication industrielle
Internet des objets industriel | Matériaux industriels | Entretien et réparation d'équipement | Programmation industrielle |
home  MfgRobots >> Fabrication industrielle >  >> Industrial programming >> Java

Java - Envoi d'e-mails

Envoyer un e-mail à l'aide de votre application Java est assez simple, mais pour commencer, vous devez disposer de l'API JavaMail et Cadre d'activation Java (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 ajouter mail.jar et activation.jar fichiers dans votre CLASSPATH.

Envoyer un e-mail simple

Voici un exemple pour envoyer un e-mail simple depuis votre machine. Il est supposé que votre localhost est connecté à Internet et suffisamment capable pour 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 −

Sortie

$ 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 identifiants d'e-mail −

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

Voici la description des paramètres −

Envoyer un e-mail HTML

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

Cet exemple est très similaire au précédent, sauf qu'ici nous utilisons 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 −

Sortie

$ java SendHTMLEmail
Sent message successfully....

Envoyer la 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 votre localhost est connecté à Internet et suffisamment capable pour 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 −

Sortie

$ java SendFileEmail
Sent message successfully....

Partie d'authentification de l'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 d'e-mails resterait comme expliqué ci-dessus.


Java

  1. Opérateurs Java
  2. Commentaires Java
  3. Java pour chaque boucle
  4. Chaînes Java
  5. InterfaceJava
  6. Classe anonyme Java
  7. Java essayer avec des ressources
  8. Annotations Java
  9. Assertions Java