Beispiel #1
0
from smtplib import SMTP

host = 'localhost'
port = 8025

client = SMTP(host, port)
client.sendmail('*****@*****.**', ['*****@*****.**'], """\
From: Anne Person <*****@*****.**>
To: Bart Person <*****@*****.**>
Subject: A test
Message-ID: <ant>

Hi Bart, this is Anne. This will fail
""")
client.sendmail('*****@*****.**', ['*****@*****.**'], """\
From: Anne Person <*****@*****.**>
To: [email protected]
Subject: A test
Message-ID: <ant>

Hi Bart, this is Anne. This will pass
""")
client.quit()
Beispiel #2
0
 def send(self):
     """Send the message."""
     try:
         smtp = SMTP(ctx.cfg['email.smtp_host'], ctx.cfg['email.smtp_port'])
     except SMTPException, e:
         raise RuntimeError(str(e))
Beispiel #3
0
    def send_email(self, backend_name, mail):
        domain = self.config.get('domain')
        recipient = self.config.get('recipient')

        parent_message = mail.parent
        references = []
        while parent_message:
            references.append(u'<%s.%s@%s>' % (backend_name, mail.parent.full_id, domain))
            parent_message = parent_message.parent
        subject = mail.title
        sender = u'"%s" <%s@%s>' % (mail.sender.replace('"', '""') if mail.sender else '',
                                    backend_name, domain)

        # assume that .date is an UTC datetime
        date = formatdate(time.mktime(utc2local(mail.date).timetuple()), localtime=True)
        msg_id = u'<%s.%s@%s>' % (backend_name, mail.full_id, domain)

        if self.config.get('html') and mail.flags & mail.IS_HTML:
            body = mail.content
            content_type = 'html'
        else:
            if mail.flags & mail.IS_HTML:
                body = html2text(mail.content)
            else:
                body = mail.content
            content_type = 'plain'

        if body is None:
            body = ''

        if mail.signature:
            if self.config.get('html') and mail.flags & mail.IS_HTML:
                body += u'<p>-- <br />%s</p>' % mail.signature
            else:
                body += u'\n\n-- \n'
                if mail.flags & mail.IS_HTML:
                    body += html2text(mail.signature)
                else:
                    body += mail.signature

        # Header class is smart enough to try US-ASCII, then the charset we
        # provide, then fall back to UTF-8.
        header_charset = 'ISO-8859-1'

        # We must choose the body charset manually
        for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
            try:
                body.encode(body_charset)
            except UnicodeError:
                pass
            else:
                break

        # Split real name (which is optional) and email address parts
        sender_name, sender_addr = parseaddr(sender)
        recipient_name, recipient_addr = parseaddr(recipient)

        # We must always pass Unicode strings to Header, otherwise it will
        # use RFC 2047 encoding even on plain ASCII strings.
        sender_name = str(Header(unicode(sender_name), header_charset))
        recipient_name = str(Header(unicode(recipient_name), header_charset))

        # Make sure email addresses do not contain non-ASCII characters
        sender_addr = sender_addr.encode('ascii')
        recipient_addr = recipient_addr.encode('ascii')

        # Create the message ('plain' stands for Content-Type: text/plain)
        msg = MIMEText(body.encode(body_charset), content_type, body_charset)
        msg['From'] = formataddr((sender_name, sender_addr))
        msg['To'] = formataddr((recipient_name, recipient_addr))
        msg['Subject'] = Header(unicode(subject), header_charset)
        msg['Message-Id'] = msg_id
        msg['Date'] = date
        if references:
            msg['In-Reply-To'] = references[0]
            msg['References'] = u" ".join(reversed(references))

        self.logger.info('Send mail from <%s> to <%s>' % (sender, recipient))
        if len(self.config.get('pipe')) > 0:
            p = subprocess.Popen(self.config.get('pipe'),
                                 shell=True,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT)
            p.stdin.write(msg.as_string())
            p.stdin.close()
            if p.wait() != 0:
                self.logger.error('Unable to deliver mail: %s' % p.stdout.read().strip())
                return False
        else:
            # Send the message via SMTP to localhost:25
            try:
                smtp = SMTP(self.config.get('smtp'))
                smtp.sendmail(sender, recipient, msg.as_string())
            except Exception as e:
                self.logger.error('Unable to deliver mail: %s' % e)
                return False
            else:
                smtp.quit()

        return True
Beispiel #4
0
# -*- coding: utf-8 -*-

# 邮件发送测试
from smtplib import SMTP


# 定义输入函数
def prompt(prompt):
    return raw_input(prompt).strip()


fromaddr = prompt("From: ")
toaddr = prompt("To:").split(",|\s")
print "Enter message, end with 'D(unix)' Or 'Z(windows)':"

msg = ("From:%s\r\nTo:%s\r\n\r\n" % (fromaddr, ",".join(toaddr)))
while True:
    try:
        line = raw_input()
    except EOFError as e:
        break
    if not line:
        break
    msg += line

print "Message length is " + repr(len(msg))

server = SMTP("localhost")
server.set_debuglevel(1)
server.sendmail(fromadd, toaddr, msg)
server.quit()
Beispiel #5
0
import os
import re
import csv
import time

from smtplib import SMTP_SSL as SMTP  # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)

# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText

with open('db.csv') as data:
    row = csv.DictReader(data)
    for line in row:
        conn = SMTP(SMTPserver)
        conn.set_debuglevel(False)
        conn.login(USERNAME, PASSWORD)
        name = line['fullname']
        add = line['email']
        text_subtype = 'html'
        content = """\

            <center><img src="https://www.edcbvucoep.com/masthead.jpg" width="631" height="273"></center>
            <br><br>
            Dear """ + name + """,<br><br>
            We, the <a href="https://www.edcbvucoep.com/">Entrepreneurship Development Cell of Bharati Vidyapeeth College of Engineering, Pune</a> is glad to invite you to it’s one of the main event, Startup Conclave 2.0 on  5th and 6th of October 2018.<br><br>
            The event will guide the participants through the journey of entrepreneurship, the importance of team-building and also host workshops on Technical and Business tracks, exciting competitions to gain a deeper understanding of these kinds of stuff.<br><br>
            On <u><strong>Day 1</strong></u> we have: <br>
            <ol>
            <li>Panel Discussion with the theme “INNOVATION and IMPACT”.
Beispiel #6
0
 def test_help_fails(self):
     with SMTP(*self.address) as client:
         code, response = client.docmd('HELP', 'HELO')
         self.assertEqual(code, 530)
Beispiel #7
0
 def test_vrfy_fails(self):
     with SMTP(*self.address) as client:
         client.ehlo('example.com')
         code, response = client.vrfy('*****@*****.**')
         self.assertEqual(code, 530)
Beispiel #8
0
def alert_smtp(alert, metric):
    """
    Called by :func:`~trigger_alert` and sends an alert via smtp to the
    recipients that are configured for the metric.

    """

    # FULL_DURATION to hours so that analyzer surfaces the relevant timeseries data
    # in the graph
    full_duration_in_hours = int(settings.FULL_DURATION) / 3600

    # For backwards compatibility
    if '@' in alert[1]:
        sender = settings.ALERT_SENDER
        recipient = alert[1]
    else:
        sender = settings.SMTP_OPTS['sender']
        recipients = settings.SMTP_OPTS['recipients'][alert[0]]

    # Backwards compatibility
    if type(recipients) is str:
        recipients = [recipients]

    graph_title = '&title=skyline%%20analyzer%%20ALERT%%20at%%20%s%%20hours%%0A%s%%20-%%20%s' % (
        str(int(full_duration_in_hours)), metric[1], metric[0])

    if settings.GRAPHITE_PORT != '':
        link = '%s://%s:%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (
            settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,
            settings.GRAPHITE_PORT, str(int(full_duration_in_hours)),
            metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
    else:
        link = '%s://%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % (
            settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST,
            str(int(full_duration_in_hours)), metric[1],
            settings.GRAPHITE_GRAPH_SETTINGS, graph_title)

    content_id = metric[1]
    image_data = None
    if settings.SMTP_OPTS.get('embed-images'):
        try:
            # @modified 20170913 - Task #2160: Test skyline with bandit
            # Added nosec to exclude from bandit tests
            image_data = urllib2.urlopen(link).read()  # nosec
        except urllib2.URLError:
            image_data = None

    # If we failed to get the image or if it was explicitly disabled,
    # use the image URL instead of the content.
    if image_data is None:
        img_tag = '<img src="%s"/>' % link
    else:
        img_tag = '<img src="cid:%s"/>' % content_id

    body = 'skyline analyzer alert <br> Anomalous value: %s <br> Next alert in: %s seconds <br> <a href="%s">%s</a>' % (
        metric[0], alert[2], link, img_tag)

    for recipient in recipients:
        msg = MIMEMultipart('alternative')
        msg['Subject'] = '[skyline alert] ' + metric[1]
        msg['From'] = sender
        msg['To'] = recipient

        msg.attach(MIMEText(body, 'html'))
        if image_data is not None:
            msg_attachment = MIMEImage(image_data)
            msg_attachment.add_header('Content-ID', '<%s>' % content_id)
            msg.attach(msg_attachment)

        s = SMTP('127.0.0.1')
        s.sendmail(sender, recipient, msg.as_string())
        s.quit()
Beispiel #9
0
from smtplib import SMTP
from poplib import POP3
from time import sleep

SMTPSVR = 'smtp.python.is.cool'
POP3SVR = 'pop.python.is.cool'

origHdrs = [
    'From: [email protected]', 'To: [email protected]',
    'Subject: test msg'
]
origBody = ['xxx', 'yyy', 'zzz']
origMsg = '\r\n\r\n'.join(['\r\n'.join(origHdrs), '\r\n'.join(origBody)])

sendSvr = SMTP(SMTPSVR)
errs = sendSvr.sendmail('*****@*****.**', ('*****@*****.**', ),
                        origMsg)
sendSvr.quit()
assert len(errs) == 0, errs
sleep(10)  # wait for mail to be delivered

recvSvr = POP3(POP3SVR)
recvSvr.user('wesley')
recvSvr.pass_('youllNeverGuess')
rsp, msg, siz = recvSvr.retr(recvSvr.stat()[0])
# strip headers and compare to orig msg
sep = msg.index('')
recvBody = msg[sep + 1:]
assert origBody == recvBody  # assert identical
Beispiel #10
0
def send_email(sender, cc_recipients, bcc_recipients, subject, body, attachments=None):
    """Send an email.

    All arguments should be Unicode strings (plain ASCII works as well).

    Only the real name part of sender and recipient addresses may contain
    non-ASCII characters.

    The email will be properly MIME encoded and delivered though SMTP to
    172.17.0.1.  This is easy to change if you want something different.

    The charset of the email will be the first one out of US-ASCII, ISO-8859-1
    and UTF-8 that can represent all the characters occurring in the email.
    """
    
    # combined recipients
    recipients = cc_recipients + bcc_recipients

    # Header class is smart enough to try US-ASCII, then the charset we
    # provide, then fall back to UTF-8.
    header_charset = 'ISO-8859-1'

    # We must choose the body charset manually
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            body.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = parseaddr(sender)
    parsed_cc_recipients = [parseaddr(rec) for rec in cc_recipients]
    parsed_bcc_recipients = [parseaddr(rec) for rec in bcc_recipients]
    #recipient_name, recipient_addr = parseaddr(recipient)

    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(Header(unicode(sender_name), header_charset))
    unicode_parsed_cc_recipients = []
    for recipient_name, recipient_addr in parsed_cc_recipients:
        recipient_name = str(Header(unicode(recipient_name), header_charset))
        # Make sure email addresses do not contain non-ASCII characters
        recipient_addr = recipient_addr.encode('ascii')
        unicode_parsed_cc_recipients.append((recipient_name, recipient_addr))
    unicode_parsed_bcc_recipients = []
    for recipient_name, recipient_addr in parsed_bcc_recipients:
        recipient_name = str(Header(unicode(recipient_name), header_charset))
        # Make sure email addresses do not contain non-ASCII characters
        recipient_addr = recipient_addr.encode('ascii')
        unicode_parsed_bcc_recipients.append((recipient_name, recipient_addr))

    # Make sure email addresses do not contain non-ASCII characters
    sender_addr = sender_addr.encode('ascii')

    # Create the message ('plain' stands for Content-Type: text/plain)
    msg = MIMEMultipart()
    msg['CC'] = COMMASPACE.join([formataddr((recipient_name, recipient_addr))
                                 for recipient_name, recipient_addr in unicode_parsed_cc_recipients])
    msg['BCC'] = COMMASPACE.join([formataddr((recipient_name, recipient_addr))
                                  for recipient_name, recipient_addr in unicode_parsed_bcc_recipients])
    msg['Subject'] = Header(unicode(subject), header_charset)
    msg['FROM'] = "*****@*****.**"
    msg.attach(MIMEText(body.encode(body_charset), 'plain', body_charset))
    
    # Add attachments
    if isinstance(attachments, types.DictType):
        for fname in attachments:
            part = MIMEBase('application', "octet-stream")
            part.set_payload(attachments[fname])
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % fname)
            msg.attach(part)

    #print "#" * 80
    #print msg.as_string()
    
    # Send the message via SMTP to docker host
    smtp_url = "smtp://%s:25" % get_container_host_ip()
    print "smtp_url : %s",smtp_url
    smtp = SMTP(get_container_host_ip())
    smtp.sendmail(sender, recipients, msg.as_string())
    smtp.quit()
Beispiel #11
0
# https://docs.python.org/3/library/smtplib.html
# smtplib 모듈은 SMTP나 ESMTP listener daemon에게 메일 전송이 가능한 SMTP 클라이언트 세션 객체이다
# RFC 821(Simple Mail Transfer Protocol), RFC 1869(SMTP Service Extensions) 기반으로 설계되어 있다
from smtplib import SMTP
from email.mime.text import MIMEText

src_email = '*****@*****.**'
dst_email = '*****@*****.**'

smtp = SMTP('smtp.naver.com', 587)
# SMTP 클래스의 인스턴스

smtp.starttls()
# tls가 필요한 경우

smtp.login('city7312', 'password')
# 로그인

message = MIMEText('내용내용', _charset='utf-8')
message['subject'] = '제목'
message['from'] = src_email
message['to'] = dst_email
# MIMEText 클래스를 이용해 제목, 송신자, 수신자를 설정

smtp.sendmail(src_email, dst_email, message.as_string())
smtp.quit()

# 추가적으로, SMTP 인스턴스는 __enter__()와 __exit__()이 구현되어 있기 때문에 with-as 문을 사용하는 것도 좋다
Beispiel #12
0
 def __init__(self, server, sender, recipients=[]):
     self.recipiends = recipiends
     self.host, self.port = server
     self.smtp = SMTP(self.host, self.port)
Beispiel #13
0
from smtplib import SMTP
from email.message import EmailMessage
from mimetypes import guess_type
import os

# SMTP协议默认端口是25
#  smtp = SMTP('smtp.exmail.qq.com', 25)
with SMTP('smtp.exmail.qq.com', 25) as smtp:
    # 为服务器通信设置调试级别
    # 1 获取与服务器交互的所有信息
    # 2 将信息带上时间戳
    smtp.set_debuglevel(2)
    smtp.login('*****@*****.**', 'Holley0719')
    smtp.sendmail('*****@*****.**',
                  ['*****@*****.**', '*****@*****.**'],
                  '1234567时光一去不复返'.encode('utf-8'))
    # 邮件主题、如何显示发件人、收件人等信息并不是通过SMTP协议发给MTA
    # 而是包含在发给MTA的文本中的
# smtp.quit()

EMAIL_CONTENT = ''
EMAIL_SETTING = {}


def send_report(file):
    msg = EmailMessage()
    msg['from'] = EMAIL_SETTING['username']
    msg['to'] = EMAIL_SETTING['receiver']
    msg['cc'] = EMAIL_SETTING['cc']
    msg['subject'] = 'xxxx'
    msg.set_boundary(EMAIL_CONTENT, 'html', 'utf-8')
Beispiel #14
0
def send_message(msg, server):
    """Sends an email using an SMTP server."""

    with SMTP(server) as s:
        s.send_message(msg)
Beispiel #15
0
 def test_forget_ehlo(self):
     with SMTP(*self.address) as client:
         client.starttls()
         code, response = client.mail('*****@*****.**')
         self.assertEqual(code, 503)
         self.assertEqual(response, b'Error: send HELO first')
Beispiel #16
0
SMTP.quit():断开smtp服务器链接
SMTP.set_debuglevel(level):设置调试输出级别,值为1,2或True,发送调试消息到服务器
SMTP.send_message(msg,from_addr=None,to_addrs=None,mail_options=[],rcpt_options=[]):这是使用有email.message.Message对象
表示的消息进行调用的便捷方法使用sendmail(),参数的含义与sendmail()相同,只有msg是一个Message对象;如果from_addr是None或者
to_addrs是None,则send_message用从msg头部提取的地址填充那些参数,from设置为发件人自动,TO设置为to_addrs。
"""
from smtplib import SMTP

HOST = "mail.woniuxy.com"  # 定义smtp主机
#SUBJECT = "测试通过Python发送邮件"  # 定义邮件主题
SUBJECT = "This is mail from Python"  # 定义邮件主题
TO = "*****@*****.**"  # 定义邮件收件人
FROM = "*****@*****.**"  # 定义邮件发件人
PASSWD = "Student123"  # 定义邮件发送人密码
#text = "这是今天Agileone项目自动化测试报告,请查收!"  # 邮件内容,编码为ASCII范围内的字符或字节字符串,所以不能写中文
text = "This is Agileone Automation Report"
BODY = '\r\n'.join((  # 组合sendmail方法的邮件主体内容,各段以"\r\n"进行分离
    "From: %s" % FROM,
    "TO: %s" % TO,
    "subject: %s" % SUBJECT,
    "",
    text
))

if __name__ == '__main__':
    server = SMTP()  # 创建一个smtp对象
    server.connect(HOST, '25')  # 链接smtp主机
    server.login(FROM, PASSWD)  # 邮箱账号登陆
    server.sendmail(FROM, TO, BODY)  # 发送邮件
    server.quit()  # 端口smtp链接
Beispiel #17
0
 def test_hello_fails(self):
     with SMTP(*self.address) as client:
         code, response = client.helo('example.com')
         self.assertEqual(code, 530)
from smtplib import SMTP

smtp = SMTP()
from_addr = "John Doe <*****@*****.**>"
to_addr = "*****@*****.**"
smtp.sendmail(from_addr, to_addr, msg)
Beispiel #19
0
 def test_ehlo(self):
     with SMTP(*self.address) as client:
         code, response = client.ehlo('example.com')
         self.assertEqual(code, 250)
         self.assertIn('starttls', client.esmtp_features)
Beispiel #20
0
def getSubject(msg, default='(no Subject line)'):
    '''\
    getSubject(msg) - iterate over 'msg' looking for
    Subject line; return if found otherwise 'default'
    '''

    for line in msg:
        if line.startswith('Subject:'):
            return line.rstrip()
        if not line:
            return default


# SMTP/TLS
print('***Doing SMTP send via TLS...')
s = SMTP('smtp.gmail.com', 587)
if release < '2.6':
    s.ehlo()  # required in older releases
s.starttls()

if release < '2.5':
    s.ehlo()  # required in older releases
s.login(MAILBOX, PASSWD)
s.sendmail(from_, to, msg)
s.quit()
print('   TLS mail sent!')

# POP
print('*** Doing POP recv...')
s = POP3_SSL('pop.gmail.com', 995)
s.user(MAILBOX)
Beispiel #21
0
 def test_data_fails(self):
     with SMTP(*self.address) as client:
         client.ehlo('example.com')
         code, response = client.docmd('DATA')
         self.assertEqual(code, 530)
Beispiel #22
0
host = "smtp.163.com"
port = 25

# BREQ_FAST mail address
recipient = '*****@*****.**'

if len(sys.argv) == 1:
    print("Usage:")
    print("  python %s mailfile ..." % sys.argv[0])
    sys.exit()
else:
    print("Total %d mails to send!" % len(sys.argv[1:]))

for mail in sys.argv[1:]:
    print("Sending %s ..." % mail)

    with open(mail) as f:
        msg = MIMEText(f.read())

    msg['From'] = sender
    msg['To'] = recipient

    with SMTP(host=host, port=port) as smtp:
        smtp.set_debuglevel(0)
        smtp.ehlo()
        smtp.starttls()
        smtp.login(sender, passwd)
        smtp.send_message(msg)

    time.sleep(random.uniform(3, 10))
Beispiel #23
0
def test_smtpdfix(msg):
    with SMTPDFix() as server, SMTP(server.hostname, server.port) as client:
        client.send_message(msg)
        assert len(server.messages) == 1
Beispiel #24
0
def botflow_execution_notification(sender, instance, **kwargs):
    try:
        smtp_account = SmtpAccount.objects.filter(activated=True)[0]
    except:
        return

    if instance.status == "Pending":
        if "@" in instance.queued_notification:
            email_subject = f"[{instance.pk}] Botflow queued: '{basename(instance.botflow)}'"
            email_to = [
                email for email in instance.queued_notification.split(",")
            ]
        else:
            return

    elif instance.status == "Running":
        if "@" in instance.started_notification:
            email_subject = f"[{instance.pk}] Botflow started: '{basename(instance.botflow)}'"
            email_to = [
                email for email in instance.started_notification.split(",")
            ]
        else:
            return

    elif instance.status == "Completed":
        if "@" in instance.completed_notification:
            email_subject = f"[{instance.pk}] Botflow completed: '{basename(instance.botflow)}'"
            email_to = [
                email for email in instance.completed_notification.split(",")
            ]
        else:
            return

    elif "ERROR" in instance.status.upper():
        if "@" in instance.error_notification:
            email_subject = f"[{instance.pk}] Botflow failed: '{basename(instance.botflow)}'"
            email_to = [
                email for email in instance.error_notification.split(",")
            ]
        else:
            return

    else:
        if "@" in instance.error_notification:
            email_subject = f"[{instance.pk}] UNKNOWN STATUS"
            email_to = [
                email for email in instance.error_notification.split(",")
            ]
        else:
            return

    try:
        email_to = [
            str(email).lower().strip() for email in email_to if "@" in email
        ]
        email_from = str(smtp_account.email).lower().strip()

        msg = EmailMessage()
        msg['Subject'] = email_subject
        msg['From'] = email_from
        msg['To'] = ", ".join(email_to)

        msg.set_content(
            f"Application: {instance.app}\nBotflow: {instance.botflow}\nTrigger: {instance.trigger}\n\nComputer Name: {instance.computer_name}\nUsername: {instance.user_name}\n\nStatus: {instance.status}\n\nTime Start: {instance.time_start}\nTime End: {instance.time_end}"
        )

        with SMTP(smtp_account.server, smtp_account.port) as server:
            if smtp_account.tls:
                server.starttls()
            if smtp_account.password != "":
                server.login(email_from, smtp_account.password)
            server.send_message(msg)

        if smtp_account.status != "Active":
            smtp_account.status = "Active"
            smtp_account.save_without_historical_record()

    except:
        if smtp_account.tls:
            try:
                msg = EmailMessage()
                msg['Subject'] = email_subject
                msg['From'] = email_from
                msg['To'] = ", ".join(email_to)

                msg.set_content(
                    f"Application: {instance.app}\nBotflow: {instance.botflow}\nTrigger: {instance.trigger}\n\nComputer Name: {instance.computer_name}\nUsername: {instance.user_name}\n\nStatus: {instance.status}\n\nTime Start: {instance.time_start}\nTime End: {instance.time_end}"
                )

                with SMTP_SSL(smtp_account.server,
                              smtp_account.port) as server:
                    if smtp_account.password != "":
                        server.login(email_from, smtp_account.password)
                    server.send_message(msg)

                if smtp_account.status != "Active":
                    smtp_account.status = "Active"
                    smtp_account.save_without_historical_record()

            except:
                if smtp_account.status != "ERROR":
                    smtp_account.status = "ERROR"
                    smtp_account.save_without_historical_record()

        else:
            if smtp_account.status != "ERROR":
                smtp_account.status = "ERROR"
                smtp_account.save_without_historical_record()
Beispiel #25
0
    def run(self):
        global block, y, es, lists, baddies, config, resendTo, timeout
        ja = []
        jas = []
        print("Thread started")
        mla = None
        ml = ""
        mboxfile = ""
        filename = ""
        xlist_override = None

        foo = archiver.Archiver(parseHTML = parseHTML)
    
        while len(lists) > 0:
            print("%u elements left to slurp" % len(lists))
            block.acquire()
            try:
                mla = lists.pop(0)
            except Exception as err:
                print("Could not pop list: %s" % err)
                block.release()
                return
            if not mla:
                print("Nothing more to do here")
                block.release()
                return
            block.release()
            y += 1
            EY = 1980
            EM = 1
            stime = time.time()
            dFile = False
            if maildir:
                messages = mailbox.Maildir(tmpname)
            elif imap:
                y -= 1 # TODO don't understand the increment above
                imap4 = mla[2]
                def mailgen(list):
                    for uid in list:
                        msgbytes = imap4.uid('fetch', uid, '(RFC822)')[1][0][1]
                        yield email.message_from_bytes(msgbytes)
                messages = mailgen(mla[0])
                xlist_override = mla[1]
            elif filebased:
                
                tmpname = mla[0]
                filename = mla[0]
                xlist_override = mla[1]
                if filename.find(".gz") != -1:
                    print("Decompressing %s..." % filename)
                    try:
                        with open(filename, "rb") as bf:
                            bmd = bf.read()
                            bf.close()
                            bmd = gzip.decompress(bmd)
                            tmpfile = tempfile.NamedTemporaryFile(mode='w+b', buffering=1, delete=False)
                            tmpfile.write(bmd)
                            tmpfile.flush()
                            tmpfile.close()
                            tmpname = tmpfile.name
                            filename = tmpname
                            dFile = True # Slated for deletion upon having been read
                            print("%s -> %u bytes" % (tmpname, len(bmd)))
                    except Exception as err:
                        print("This wasn't a gzip file: %s" % err )
                print("Slurping %s" % filename)
                messages = mailbox.mbox(tmpname)

            else:
                ml = mla[0]
                mboxfile = mla[1]
                xlist_override = list_override
                print("Slurping %s/%s" % (ml, mboxfile))
                m = re.match(r"(\d\d\d\d)(\d\d)", mboxfile)
                EY = 1997
                EM = 1
                if m:
                    EY = int(m.group(1))
                    EM = int(m.group(2))
                ctx = urlopen("%s%s/%s" % (source, ml, mboxfile ))
                inp = ctx.read().decode(ctx.headers.get_content_charset() or 'utf-8', errors='ignore')
    
                tmpname = hashlib.sha224(("%f-%f-%s-%s.mbox" % (random.random(), time.time(), ml, mboxfile)).encode('utf-8') ).hexdigest()
                with open(tmpname, "w") as f:
                    f.write(inp)
                    f.close()
                messages = mailbox.mbox(tmpname)

            count = 0
            LEY = EY

            for message in messages:
                if resendTo:
                    print("Delivering message %s via MTA" % message['message-id'] if 'message-id' in message else '??')
                    s = SMTP('localhost')
                    try:
                        if list_override:
                            message.replace_header('List-ID', list_override)
                        message.replace_header('To', resendTo)
                    except:
                        if list_override:
                            message['List-ID'] = list_override
                    message['cc'] = None
                    s.send_message(message, from_addr=None, to_addrs=(resendTo))
                    continue
                if (time.time() - stime > timeout): # break out after N seconds, it shouldn't take this long..!
                    print("Whoa, this is taking way too long, ignoring %s for now" % tmpname)
                    break

                json, contents = foo.compute_updates(list_override, private, message)

                if json:
                    json_source = {
                        'mid': json['mid'],
                        'message-id': json['message-id'],
                        'source': message.as_bytes().decode('utf-8', errors='replace')
                    }

                    count += 1
                    ja.append(json)
                    jas.append(json_source)
                    if contents:
                        iname = config.get("elasticsearch", "dbname")
                        if not args.dry:
                            for key in contents:
                                es.index(
                                    index=iname,
                                    doc_type="attachment",
                                    id=key,
                                    body = {
                                        'source': contents[key]
                                    }
                                )
                    if len(ja) >= 40:
                        if not args.dry:
                            bulk = BulkThread()
                            bulk.assign(ja, es, 'mbox')
                            bulk.insert()
                        ja = []
                        
                        if not args.dry:
                            bulks = BulkThread()
                            bulks.assign(jas, es, 'mbox_source')
                            bulks.insert()
                        jas = []
                else:
                    baddies += 1

            if filebased:
                print("Parsed %u records from %s" % (count, filename))
                if dFile:
                    os.unlink(tmpname)
            elif imap:
                print("Parsed %u records from imap" % count)
            else:
                print("Parsed %s/%s: %u records from %s" % (ml, mboxfile, count, tmpname))
                os.unlink(tmpname)
                
            y += count
            if not args.dry:
                bulk = BulkThread()
                bulk.assign(ja, es)
                bulk.insert()
            ja = []
            
            if not args.dry:
                bulks = BulkThread()
                bulks.assign(jas, es, 'mbox_source')
                bulks.insert()
            jas = []
        print("Done, %u elements left to slurp" % len(lists))
Beispiel #26
0
def send_email(prefs, report_str):
    recipients = prefs['ADMIN_EMAIL'].split(',')

    msg = dedent("""
        From: {0}
        To: {1}
        Subject: {2}
        Date: {3}

        """).lstrip().format(prefs.get('SMTP_FROM'), prefs.get('ADMIN_EMAIL'),
                             prefs.get('SMTP_SUBJECT'),
                             time.strftime(prefs.get('SMTP_DATE_FORMAT')))

    msg += report_str
    try:
        if is_true(prefs.get('SMTP_SSL')):
            smtp = SMTP_SSL()
        else:
            smtp = SMTP()

        if logging.getLogger().isEnabledFor(logging.DEBUG):
            smtp.set_debuglevel(1)

        smtp.connect(prefs.get('SMTP_HOST'), prefs.get('SMTP_PORT'))

        # If the server supports ESMTP and TLS, then convert the message exchange to TLS via the
        # STARTTLS command.
        if smtp.ehlo()[0] == 250:
            if smtp.has_extn('starttls'):
                (code, resp) = smtp.starttls()
                if code != 220:
                    raise SMTPResponseException(code, resp)
                (code, resp) = smtp.ehlo()
                if code != 250:
                    raise SMTPResponseException(code, resp)
        else:
            # The server does not support esmtp.

            # The Python library SMTP class handles executing HELO/EHLO commands inside
            # login/sendmail methods when neither helo()/ehlo() methods have been
            # previously called.  Because we have already called ehlo() above, we must
            # manually fallback to calling helo() here.

            (code, resp) = smtp.helo()
            if not (200 <= code <= 299):
                raise SMTPHeloError(code, resp)

        username = prefs.get('SMTP_USERNAME')
        password = prefs.get('SMTP_PASSWORD')

        if username and password:
            smtp.login(username, password)

        smtp.sendmail(prefs.get('SMTP_FROM'), recipients, msg)
        debug("sent email to: %s" % prefs.get("ADMIN_EMAIL"))
    except Exception as e:
        print("Error sending email")
        print(e)
        print("Email message follows:")
        print(msg)

    try:
        smtp.quit()
    except Exception:
        pass
Beispiel #27
0
 def __init__(self, smtp, port):
     self.server = SMTP(smtp, port)
Beispiel #28
0
 def send_message(self, host, port, msg):
     with SMTP(host, port) as smtp_client:
         smtp_client.send_message(msg)
Beispiel #29
0
    def send_email(self, message, customizations=None):
        md = markdown.Markdown()

        if isinstance(customizations, dict):
            from_address = customizations.get('from', self.config['from'])
        else:
            from_address = self.config['from']

        start = time.time()
        m = MIMEMultipart('alternative')

        priority = message.get('priority')
        if priority:
            m['X-IRIS-PRIORITY'] = priority

        application = message.get('application')
        if application:
            m['X-IRIS-APPLICATION'] = application

        plan = message.get('plan')
        if plan:
            m['X-IRIS-PLAN'] = plan

        incident_id = message.get('incident_id')
        if incident_id:
            m['X-IRIS-INCIDENT-ID'] = str(incident_id)

        m['Date'] = formatdate(localtime=True)
        m['from'] = from_address
        m['to'] = message['destination']
        if message.get('noreply'):
            m['reply-to'] = m['to']

        if 'email_subject' in message:
            m['subject'] = message['email_subject']
        else:
            m['subject'] = message['subject']

        plaintext = None

        if 'email_text' in message:
            plaintext = message['email_text']
        elif 'body' in message:
            plaintext = message['body']

        if plaintext:
            mt = MIMEText(None, 'plain', 'utf-8')
            mt.set_payload(quopri.encodestring(plaintext.encode('UTF-8')))
            mt.replace_header('Content-Transfer-Encoding', 'quoted-printable')
            m.attach(mt)

        # for tracking messages, email_html is not required, so it's possible
        # that both of the following keys are missing from message
        html = None

        if 'email_html' in message:
            html = message['email_html']
        elif 'body' in message:
            html = md.convert(message['body'])

        if html:
            if 'extra_html' in message:
                html += message['extra_html']
            # We need to have body tags for the oneclick buttons to properly parse
            html = '<body>\n' + html + '\n</body>'
            mt = MIMEText(None, 'html', 'utf-8')
            # Google does not like base64 encoded emails for the oneclick button functionalty,
            # so force quoted printable.
            mt.set_payload(quopri.encodestring(html.encode('UTF-8')))
            mt.replace_header('Content-Transfer-Encoding', 'quoted-printable')
            m.attach(mt)

        conn = None

        # Try reusing previous connection in this worker if we have one
        if self.last_conn:
            conn = self.last_conn
        else:
            for mx in self.mx_sorted:
                try:
                    smtp = SMTP(timeout=self.smtp_timeout)
                    smtp.connect(mx[1], self.config.get('port', 25))
                    if self.config.get('username',
                                       None) is not None and self.config.get(
                                           'password', None) is not None:
                        smtp.login(self.config.get('username', None),
                                   self.config.get('password', None))
                    conn = smtp
                    self.last_conn = conn
                    self.last_conn_server = mx[1]
                    break
                except Exception as e:
                    logger.exception(e)

        if not conn:
            raise Exception('Failed to get smtp connection.')

        try:
            conn.sendmail([from_address], [message['destination']],
                          m.as_string())
        except Exception:
            logger.warning(
                'Failed sending email through %s. Will try connecting again and resending.',
                self.last_conn_server)

            try:
                conn.quit()
            except Exception:
                pass

            # If we can't send it, try reconnecting and then sending it one more time before
            # giving up
            for mx in self.mx_sorted:
                try:
                    smtp = SMTP(timeout=self.smtp_timeout)
                    smtp.connect(mx[1], 25)
                    conn = smtp
                    self.last_conn = conn
                    self.last_conn_server = mx[1]
                    break
                except Exception as e:
                    logger.exception(
                        'Failed reconnecting to %s to send message',
                        self.last_conn_server)
                    self.last_conn = None
                    return None

            try:
                # If configured, sleep to back-off on connection
                if self.retry_interval:
                    sleep(self.retry_interval)
                conn.sendmail([from_address], [message['destination']],
                              m.as_string())
                logger.info(
                    'Message successfully sent through %s after reconnecting',
                    self.last_conn_server)
            except Exception:
                logger.exception(
                    'Failed sending email through %s after trying to reconnect',
                    self.last_conn_server)
                return None

        return time.time() - start
Beispiel #30
0
from smtplib import SMTP

sender = "*****@*****.**"

msg = """From: From Person <*****@*****.**>
To: To Person <*****@*****.**>
Subject: SMTP e-mail test

This is a test e-mail message.
"""
smtpConnection = SMTP(host='localhost', port=1025)
smtpConnection.sendmail(sender, sender, msg)