Skip to content
Snippets Groups Projects
MailUtil.java 2.3 KiB
Newer Older
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package MailUtil;

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

/**
 *
 * @author lmasson
 */
public class MailUtil {
    private static String USER_NAME = "plantequipleure";  // GMail user name (just the part before "@gmail.com")
    private static String PASSWORD = "cryingplant12"; // GMail password
    private static String RECIPIENT = "puissegur.alexis@gmail.com";
tcoulin's avatar
tcoulin committed
    public static void sendDistressMail(String humidityPlant, String humiditySeuil) {

        String from = USER_NAME;
        String pass = PASSWORD;
        String subject = "Votre plante pleure";
tcoulin's avatar
tcoulin committed
        String txt = "J'en ai marre que tu oublies tout le temps de m'arroser. J'ai soif !\n"+
                "mon humidité est de : "+humidityPlant+"% \n"+
                "tu as défini un seuil de : "+humiditySeuil+"%";
tcoulin's avatar
tcoulin committed
        sendFromGMail(from, pass, RECIPIENT, subject, txt);
    }

    private static void sendFromGMail(String from, String pass, String to, String subject, String body) {
        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress toAddress = new InternetAddress(to);

            message.addRecipient(Message.RecipientType.TO, toAddress);

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }
        catch (AddressException ae) {
            ae.printStackTrace();
        }
        catch (MessagingException me) {
            me.printStackTrace();
        }
    }
tcoulin's avatar
tcoulin committed