package org.bdware.sc.boundry.utils;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Properties;

public class EmailUtil {
    public static String sendEmail(String json) {
        try {
            final JsonObject jo = JsonParser.parseString(json).getAsJsonObject();
            Properties props = new Properties();
            props.setProperty("mail.debug", "false");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.host", jo.get("host").getAsString());
            props.setProperty("mail.smtp.port", jo.get("port").getAsString());
            props.setProperty("mail.transport.protocol", "smtp");
            props.put("mail.smtp.auth", "true");
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.port", jo.get("port").getAsString());
            Session session =
                    Session.getDefaultInstance(
                            props,
                            new Authenticator() {
                                public PasswordAuthentication getPasswordAuthentication() {
                                    return new PasswordAuthentication(
                                            jo.get("from").getAsString(),
                                            jo.get("pwd").getAsString()); // 发件人邮件用户名、密码
                                }
                            });
            // 创建邮件对象

            Message msg = new MimeMessage(session);
            msg.setSubject(jo.get("subject").getAsString());
            msg.setText(jo.get("content").getAsString());
            msg.setFrom(new InternetAddress(jo.get("from").getAsString()));
            msg.addRecipient(
                    Message.RecipientType.TO, new InternetAddress(jo.get("to").getAsString()));
            Transport.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
        return "success";
    }
}
