import * as nodemailer from 'nodemailer';
import * as smtpMail from 'nodemailer-smtp-transport';

import { SMTPDATA, MAILDATA } from './config'
import {EmailAddress} from './global/scalars/EmailAddress'

export const sendmail = (to: EmailAddress, subject: string, text: string, cc?: string, bcc?: string, from?: string) => {
    const transporter = nodemailer.createTransport(smtpMail({
        host: SMTPDATA.host,
        port: SMTPDATA.port,
        secure: SMTPDATA.secure, // use TLS
        auth: {
            user: SMTPDATA.user,
            pass: SMTPDATA.pwd,
        },
        tls: {
            rejectUnauthorized: false
        }
    }))

    const sender = `"${MAILDATA.name}" <${MAILDATA.address}>`;
    const mailOptions: any = {
        from: sender,
        to,
        cc: cc ? cc : '',
        bcc: bcc ? bcc : '',
        subject,
        text,
    };

    if(from) {
        mailOptions.replyTo = from;
    }

    transporter.sendMail(mailOptions, (err) => {
        if (err) {
            console.log('Fehler: ' + err);
        }
    })
}