Python Send Mail With Function

Aşağıdaki Python kodunu kullanarak, parametrik olarak mail gönderebiliriz.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def sendMailForHTML(html, subj, mail_server_config, mail_from_to):

    server_ip = mail_server_config["server_ip"]
    server_port = mail_server_config["server_port"]
    mail_server_username = mail_server_config["mail_server_username"]
    mail_server_pass = mail_server_config["mail_server_pass"]

    from_email = mail_from_to["from_email"]
    to_email = mail_from_to["to_email"]

    # send mail section
    try:
        server = smtplib.SMTP(server_ip, server_port)
        # server.set_debuglevel(1)

        server.connect(server_ip, server_port)
        server.ehlo()
        server.starttls()
        server.ehlo()

        # Next, log in to the server
        server.login(mail_server_username, mail_server_pass)
        print("Mail server connection successful...")

        msg = MIMEMultipart('alternative')

        if html is not None:
            msg['Subject'] = subj
            msg['From'] = from_email
            msg['To'] = ','.join(to_email)

            html_text = MIMEText(html.encode('utf-8'), 'html', 'utf-8')

            msg.attach(html_text)
            # Send the mail
            server.sendmail(from_email, to_email, msg.as_string())
            print("Mail sent successfully...")
        else:
            print("Nothing to send with email..")
    except smtplib.SMTPException as e:
        print("Something wrong with SMTP server : " + str(e))


# mail config
mail_config = {
    "server_ip": "mail_server",
    "server_port": PORT_NUMBER,
    "mail_server_username": "[email protected]",
    "mail_server_pass": "password"
}

from_to = {
    "from_email": "[email protected]",
    "to_email": ['[email protected]']
}

subj = "Subject"
html = "HTML Mail Content"

sendMailForHTML(html, subj, mail_config, from_to)

Leave a Comment