<commit_before>#!/usr/bin/env python

from consolemsg import step

htmltemplate = """\
<html>
<head>
<style>
em {{
    color: red;
}}
strong {{
    color: green;
}}
</style>
</head>
<body>
{}
</body>
</html>
"""



def sendMail(
        sender,
        recipients,
        subject,
        text=None,
        html=None,
        md=None,
        cc=[],
        bcc=[],
        replyto=[],
        attachments = [],
        template=None,
        params = {},
        ):

    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email import Encoders

    from config import smtp

    msg = MIMEMultipart()
    msg['Subject'] = subject 
    msg['From'] = sender
    msg['To'] = ', '.join(recipients)
    if cc: msg['CC'] = ', '.join(cc)
    if bcc: msg['BCC'] = ', '.join(bcc)
    if replyto: msg['Reply-To'] = ', '.join(replyto)


    for filename in attachments:
        step("Attaching {}...".format(filename))
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(filename, "rb").read())
        Encoders.encode_base64(part)

        part.add_header(
            'Content-Disposition',
            'attachment; filename="{}"'.format(filename.replace('"', '')))

        msg.attach(part)

    if md:
        import premailer
        import markdown
        text = md
        html = premailer.transform(
            htmltemplate.format(
                markdown.markdown(md, output_format='html')
            ))

    content = MIMEMultipart('alternative')

    if text:
        content.attach(MIMEText(text,'plain'))

    if html:
        content.attach(MIMEText(html,'html'))

    msg.attach(content)

    step("Connecting to {host}:{port} as {user}...".format(**smtp))
    server = smtplib.SMTP(smtp['host'], smtp['port'])
    server.starttls()
    server.login(smtp['user'], smtp['password'])
    step("Sending...")
    server.sendmail(sender, recipients, msg.as_string())
    step("Disconnecting...")
    server.quit()


def main():
    import glob
    import sys

    args = parseArgs()
    print args

    content = {}
    content[args.format] = sys.stdin.read()
    print content

    sendMail(
        sender = args.sender,
        recipients = args.recipients,
        subject = args.subject,
        cc = args.cc,
        bcc = args.bcc,
        replyto = args.replyto,
        attachments = args.attachments,
        template = args.template,
        **content)

    return

    sendMail(
        sender = '<EMAIL>',
        subject = 'Prova html amb head i comment',
        recipients = [
            '<EMAIL>',
            ],
        bcc = [
            '<EMAIL>',
            ],
        replyto = [
            '<EMAIL>',
            ],
        md = """\
Queridos reyes _magos_,

Me he portado **fatal**
""",
        attachments= glob.glob("*.svg")[:4],
        )

def parseArgs():
    import argparse
    parser = argparse.ArgumentParser(
        description="Sends an email.",
        )
    parser.add_argument(
        '--from',<commit_msg>sendmail: removing example, body by command line<commit_after>#!/usr/bin/env python

from consolemsg import step

htmltemplate = """\
<html>
<head>
<style>
em {{
    color: red;
}}
strong {{
    color: green;
}}
</style>
</head>
<body>
{}
</body>
</html>
"""



def sendMail(
        sender,
        recipients,
        subject,
        text=None,
        html=None,
        md=None,
        cc=[],
        bcc=[],
        replyto=[],
        attachments = [],
        template=None,
        params = {},
        ):

    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email import Encoders

    from config import smtp

    msg = MIMEMultipart()
    msg['Subject'] = subject 
    msg['From'] = sender
    msg['To'] = ', '.join(recipients)
    if cc: msg['CC'] = ', '.join(cc)
    if bcc: msg['BCC'] = ', '.join(bcc)
    if replyto: msg['Reply-To'] = ', '.join(replyto)


    for filename in attachments:
        step("Attaching {}...".format(filename))
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(filename, "rb").read())
        Encoders.encode_base64(part)

        part.add_header(
            'Content-Disposition',
            'attachment; filename="{}"'.format(filename.replace('"', '')))

        msg.attach(part)

    if md:
        import premailer
        import markdown
        text = md
        html = premailer.transform(
            htmltemplate.format(
                markdown.markdown(md, output_format='html')
            ))

    content = MIMEMultipart('alternative')

    if text:
        content.attach(MIMEText(text,'plain'))

    if html:
        content.attach(MIMEText(html,'html'))

    msg.attach(content)

    step("Connecting to {host}:{port} as {user}...".format(**smtp))
    server = smtplib.SMTP(smtp['host'], smtp['port'])
    server.starttls()
    server.login(smtp['user'], smtp['password'])
    step("Sending...")
    server.sendmail(sender, recipients, msg.as_string())
    step("Disconnecting...")
    server.quit()


def main():
    import sys

    args = parseArgs()
    print args

    if args.body is not None:
        content = args.body
    elif args.bodyfile is not None:
        with open(args.bodyfile) as f:
            content = f.read()
    else:
        content = sys.stdin.read()

    print content

    sendMail(
        sender = args.sender,
        recipients = args.recipients,
        subject = args.subject,
        cc = args.cc,
        bcc = args.bcc,
        replyto = args.replyto,
        attachments = args.attachments,
        template = args.template,
        **{args.format: content}
        )


def parseArgs():
    import argparse
    parser = argparse.ArgumentParser(
        description="Sends an email.",
        )
    parser.add_argument(
        '--from',
{'fraction_non_alphanumeric': 0.14479638009049775, 'fraction_numerical': 0.0008379420144126027, 'mean_word_length': 2.0858324715615306, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3334809', 'n_tokens_mistral': 1898, 'n_tokens_neox': 1849, 'n_words': 403}