mallek-ahmed / Git-Repo

0 stars 0 forks source link

Java : EmailSender #16

Open mallek-ahmed opened 1 year ago

mallek-ahmed commented 1 year ago

import javax.mail.; import javax.mail.internet.;

import java.util.Properties;

public class EmailSender { public static void main(String[] args) { // Paramètres du serveur SMTP String host = "smtp.mailserver.com"; String port = "587"; String mailFrom = "sender@example.com"; String password = "password";

    // Adresses email du destinataire
    String mailTo = "recipient@example.com";
    String subject = "Sujet du mail";
    String message = "Message du mail";

    try {
        // configurations des propriétés
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        // Création d'une nouvelle session avec une authentification
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mailFrom, password);
            }
        };
        Session session = Session.getInstance(properties, auth);

        // Création d'un nouveau message email
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(mailFrom));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
        msg.setSubject(subject);
        msg.setText(message);

        // Envoie du message
        Transport.send(msg);

        System.out.println("Mail envoyé avec succès");

    } catch (Exception ex) {
        System.out.println("Echec de l'envoi du mail");
        ex.printStackTrace();
    }
}

}

mallek-ahmed commented 1 year ago
javax.mail javax.mail-api 1.6.2 com.sun.mail javax.mail 1.6.2 javax.activation activation 1.1.1