package dev.ksan.etfoglasiserver.service;

import org.simplejavamail.api.email.Email;
import org.simplejavamail.api.mailer.Mailer;
import org.simplejavamail.api.mailer.config.TransportStrategy;
import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.mailer.MailerBuilder;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

@Service
public class MailService {
    String address;
    String passwd;
    Mailer mailer;

    public MailService(){
        this(".creds");
    }
    public MailService(String filename) {
        try(BufferedReader br = new BufferedReader((new FileReader(filename)))) {
            address = br.readLine();
            passwd = br.readLine();
        }catch(IOException e) {
            e.printStackTrace();
        }
        this.mailer =   MailerBuilder
                .withSMTPServer("smtp.gmail.com",587,address,passwd)
                .withTransportStrategy(TransportStrategy.SMTP)
                .withSessionTimeout(10_000).buildMailer();
    }

    public void sendEmail(String to, String subject, String body) {
        Email email = EmailBuilder.startingBlank()
                .from(address).to(to)
                .withSubject(subject)
                .withPlainText(body).buildEmail();

        mailer.sendMail(email);
    }
}
