import smtplib, sys
from email.mime.text import MIMEText
from email.header import Header

# Credentials and message
HOSTS = ['smp.nepirity.com', 'smtp.nepirity.com']
USER = 'noreply'
PASSWORD = 'nepirity1234!!'
FROM = 'noreply@nepirity.com'
TO = 'ikseon1026@gmail.com'
SUBJECT = '[테스트] 메일 발송 확인 - zeroclaw'
BODY = '이 메일은 zeroclaw가 테스트로 발송한 메일입니다.\n\n감사합니다.'

ports_and_methods = [
    (25, False, True),    # try STARTTLS on 25
    (587, False, True),   # port, use_ssl, starttls
    (465, True, False),   # SMTPS
    (25, False, False),   # plain
]


def try_send(host, port, use_ssl=False, starttls=False):
    try:
        if use_ssl:
            s = smtplib.SMTP_SSL(host, port, timeout=15)
        else:
            s = smtplib.SMTP(host, port, timeout=15)
        s.set_debuglevel(1)
        if starttls:
            s.ehlo()
            s.starttls()
            s.ehlo()
        s.login(USER, PASSWORD)
        msg = MIMEText(BODY, 'plain', 'utf-8')
        msg['From'] = FROM
        msg['To'] = TO
        msg['Subject'] = Header(SUBJECT, 'utf-8')
        s.sendmail(FROM, [TO], msg.as_string())
        s.quit()
        print('OK: host=%s port=%s ssl=%s starttls=%s' % (host, port, use_ssl, starttls))
        return True
    except Exception as e:
        print('ERR: host=%s port=%s ssl=%s starttls=%s -> %s' % (host, port, use_ssl, starttls, e))
        return False


if __name__ == '__main__':
    for host in HOSTS:
        for port, use_ssl, starttls in ports_and_methods:
            ok = try_send(host, port, use_ssl=use_ssl, starttls=starttls)
            if ok:
                sys.exit(0)
    print('ALL FAILED')
    sys.exit(2)
