Example #1
2
def send(server, from_addr, to_addrs, subject, msg_text, msg_html,
        cc_addrs = None, bcc_addrs = None):
    """ Sends an email to a set of recipients by using a SMTP sever

        from_addr -- The email address of the sender
        to_addsr -- A list of destination email addresses
        subject -- Subject of the email
        msg_text -- The email message in plain text format
        msg_html -- THe email message in HTML format
        cc_addrs -- A list of CC destination email addresses
        bcc_addrs -- A list of BCC destination email addresses
    """

    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = ','.join(to_addrs)
    if (cc_addrs and len(cc_addrs) > 0):
        msg['Cc'] = ','.join(cc_addrs)
    if (bcc_addrs and len(bcc_addrs) > 0):
        msg['Bcc'] = ','.join(bcc_addrs)

    # Record the MIME types of both parts - text/plain and text/html.
    part1 = MIMEText(unicode(msg_text).encode('utf-8'), 'plain')
    part2 = MIMEText(unicode(msg_html).encode('utf-8'), 'html')

    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.attach(part1)
    msg.attach(part2)
 
    server.sendmail(from_addr, to_addrs, msg.as_string())
Example #2
0
def send(subject, body, filename):
    if hasattr(config, 'alarm_email') and hasattr(config, 'gmail_user') and hasattr(config, 'gmail_pass'):

        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = config.gmail_user
        msg['To'] = config.alarm_email

        text = MIMEText(body)
        msg.attach(text)
        with open(filename, 'rb') as img_f:
            image = MIMEImage(img_f.read(), name=os.path.basename('img.jpg'))
            msg.attach(image)

        try:
            # Allow access for less secure apps in your Google account, otherwise exception is thrown
            s = smtplib.SMTP('smtp.gmail.com', 587)
            s.ehlo()
            s.starttls()
            s.login(config.gmail_user, config.gmail_pass)
            s.sendmail(msg['From'], msg['To'], msg.as_string())
            s.quit()
            main_logger.info('sent mail to %s' % config.alarm_email)
        except:
            main_logger.error('failed to send mail to %s' % config.alarm_email)
            traceback.print_exc()
def notify(pancakes, recipients):
    """Sends digest email(s) to recipients given pancakes (no email sent if pancakes is empty)."""
    if not pancakes:
        return

    plain = text_digest(pancakes)
    log.info('digest:\n{}'.format(plain))

    if not recipients:
        return

    msg = MIMEMultipart('alternative')
    msg['Subject'] = 'Pancake Master: {}'.format(datetime_string(datetime.now()))
    msg['To'] = 'undisclosed-recipients'
    msg['From'] = recipients[0]
    msg.attach(MIMEText(plain, 'plain'))
    msg.attach(MIMEText(html_digest(pancakes), 'html'))

    try:
        s = smtplib.SMTP('localhost')
        s.set_debuglevel(1)
        s.login(load_user(), load_pass())
        s.sendmail(msg['From'], recipients, msg.as_string())
        s.quit()
        log.info('sent email(s) to {}'.format(', '.join(recipients)))
    except Exception as e:
        log.error('email fail: {}'.format(e))
        raise
Example #4
0
    def _send_alerts_if_any(self, alerts_to_send_map):
        """Evaluate if there are news to send. If that is the case, send the alerts.
        This version only supports lists grouped by email."""
        for email_to_string, alert_event_list in alerts_to_send_map.iteritems():
            if not self._is_something_to_report(alert_event_list):
                continue
            html_version_main = self._html_version_main()
            html_version_items = self._html_version_items(alert_event_list)
            html_version = html_version_main.format(html_version_items=html_version_items,
                                                    # TODO Externalize variables
                                                    date=datetime.datetime.now().strftime("%B %d, %Y"),
                                                    time=datetime.datetime.now().strftime("%I:%M %p"),
                                                    message_signature=hashlib.sha256(html_version_main + html_version_items + datetime.datetime.now().strftime("%B %d, %Y - %I:%M %p")).hexdigest(),
                                                    companyName=""
                                                    )
            # text_version = bs.get_text()

            # create email
            email = MIMEMultipart('alternative')
            # TODO calculate this value.
            email['Subject'] = "monitoring alert"
            email['From'] = self.email_from
            # email_to = email_to_string.split(',')
            email['To'] = email_to_string
            # part_text = MIMEText(text_version, 'plain', 'utf-8')
            # email.attach(part_text)
            part_html = MIMEText(html_version, 'html', 'utf-8')
            email.attach(part_html)

            self._send_email(email, email_to_string)
def send_mail(subject, text, html=None):
    
    if not get_setting('enabled'):
        print('email not enabled')
        return
    encryption = (get_setting('encryption') or '').lower()
    host = get_setting('host')
    port = int(get_setting('port'))
    if encryption == 'ssl':
        smtp = smtplib.SMTP_SSL(host=host, port=port)
    else:
        smtp = smtplib.SMTP(host=host, port=port)

    if encryption == 'tls':
        smtp.starttls()

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

    _from = get_setting('from name') or 'GarageWarden'
    recipients = get_setting('recipients')
    msg = MIMEMultipart("alternative")
    msg['Subject'] = subject
    msg['From'] = _from
    msg['To'] = recipients
    if text:
        msg.attach(MIMEText(text, "plain"))
    if html:
        msg.attach(MIMEText(html, "html"))
    smtp.sendmail(_from, [r.strip() for r in recipients.split(',') if r], msg.as_string())
Example #6
0
    def smtpSendWithFile(self, toList, sub, att):
        msg = MIMEMultipart()
        me = 'Ming<{0}@{1}>'.format(self.mail_user,self.mail_postfix)
        msg['Subject'] = Header(sub,'utf-8')
        msg['From'] = me
        msg['To'] = ','.join(toList)
        #with open(att,'rb') as fp:
        #    content = MIMEBase('application', 'octet-stream')
        #    content.set_payload(fp.read())
        with open(att,'rb') as fp:
            content = MIMEText(fp.read(), _subtype = 'plain', _charset = 'utf-8')
        #encoders.encode_base64(content)
        fileName = '{0}_{1}'.format(sub, os.path.basename(att))
        content.add_header('Content-Disposition', 'attachment', filename = fileName)
        msg.attach(content)
        composed = msg.as_string()
        try:
          s = smtplib.SMTP()
          s.connect(self.mailHost)
          s.login(self.mail_user, self.mail_pwd)
          s.sendmail(me, toList, composed)
          s.close()
          return True
        except Exception as e:
          print(str(e))
          return False

#monitor = WinMonitorClass()
#content = "This is only a test mail sent by Python. Click following link to go to <a href='http://www.baidu.com'>百度</a>"
##monitor.imapHelper()
#mailtoList = [r'*****@*****.**', r'*****@*****.**',r'*****@*****.**']
#if monitor.smtpSend(mailtoList, "Hello SMTP!", content):
#    print("Send Successfully...")
#else:
#    print("Send Mail Failed!!!")
Example #7
0
    def test_mixed_cloud_config(self):
        blob_cc = """
#cloud-config
a: b
c: d
"""
        message_cc = MIMEBase("text", "cloud-config")
        message_cc.set_payload(blob_cc)

        blob_jp = """
#cloud-config-jsonp
[
     { "op": "replace", "path": "/a", "value": "c" },
     { "op": "remove", "path": "/c" }
]
"""

        message_jp = MIMEBase("text", "cloud-config-jsonp")
        message_jp.set_payload(blob_jp)

        message = MIMEMultipart()
        message.attach(message_cc)
        message.attach(message_jp)

        ci = stages.Init()
        ci.datasource = FakeDataSource(str(message))
        new_root = self.makeDir()
        self.patchUtils(new_root)
        self.patchOS(new_root)
        ci.fetch()
        ci.consume_userdata()
        cc_contents = util.load_file(ci.paths.get_ipath("cloud_config"))
        cc = util.load_yaml(cc_contents)
        self.assertEquals(1, len(cc))
        self.assertEquals("c", cc["a"])
def send_mail(_from_, to_, subject, text, files=None, server=config.MAIL_SERVER, port=config.MAIL_SERVER_PORT):
    assert isinstance(to_, (list, tuple))

    if files is None:
        files = []

    msg = MIMEMultipart()
    msg['From'] = _from_
    msg['To'] = COMMASPACE.join(to_)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for file_name, file_content in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( file_content )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % file_name)
        msg.attach(part)

    smtp = smtplib.SMTP(server, port=port)
    smtp.sendmail(_from_, to_, msg.as_string() )
    smtp.close()
 def setUp(self):
     
     #set up the image for the message
     ePic = 'v:/workspace/HandlingEmail_Homework/src/python-logo.png'
     att = open(ePic, 'rb')
     img = MIMEImage(att.read())
     att.close()
     img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(ePic))
     
     #set up the message body
     msgText = MIMEText("This is a test string", 'plain')
     
     #build the message
     msg = MIMEMultipart()
     msg['To'] = '*****@*****.**'
     msg['From'] = '*****@*****.**'
     msg['Subject'] = 'Test Email'
     msg.attach(msgText)
     msg.attach(img)
     self.Mmsg = msg
     
     #create a set for comparison
     self.attachmentSet = {msgText.as_string(), img.as_string()}
     
     #engages the function
     attachments = [ePic]
     mailObj = emailReturn('*****@*****.**', 'This is a test string', attachments)
     self.mailTest = mailObj
Example #10
0
    def send_raw_email(self, **kwargs):
        ''' still in dev '''
        msg_all = MIMEMultipart()
        msg_all['From'] = kwargs['source']
        msg_all['To'] = kwargs['to_addresses']
        msg_all['Subject'] = kwargs['subject']

        msg_all.attach(MIMEText("""123國<br><a href="http://toomore.net/">link</a>""", 'html', 'utf-8'))

        ics = render_ics(
            title=u'吃火鍋',
            description=u'冬天到了要吃火鍋!',
            location=u'台北市中正區衡陽路51號',
            start=datetime(2015, 1, 29, 10),
            end=datetime(2015, 1, 29, 18, 30),
            created=None,
            admin=u'Toomore',
            admin_mail=u'*****@*****.**',
            url=u'http://toomore.net/'
        )
        attachment = MIMEBase('text', 'calendar; name=calendar.ics; method=REQUEST; charset=UTF-8')
        attachment.set_payload(ics.encode('utf-8'))
        encoders.encode_base64(attachment)
        attachment.add_header('Content-Disposition', 'attachment; filename=%s' % "calendar.ics")

        msg_all.attach(attachment)

        return super(AwsSESTools, self).send_raw_email(msg_all.as_string(), kwargs['source'])
Example #11
0
    def send(self):
        msg = MIMEMultipart()   
        msg['From'] = self.sender  
        msg['To'] = ';'.join(self.to_list)
        msg['Subject'] = self.subject   
        
        result_list = self.body        
        text = "Single user try " + ("succeed.\n" if result_list[0] else "failed.\n")
        for sub_list in result_list[1:]:
            text += ("  [ PASS ] " if sub_list[1] else "  [FAILED] ") + "Script: " + sub_list[0] + "\n"
            if not sub_list[1]:
                for item in sub_list[2:]:
                    if item[2]:
                        text += "    Transaction: \"" + item[0] + "\" failed.\n"
        
        msg.attach(MIMEText(text,_charset='utf-8'))

        logger.info("E-mail - Server: " + self.server)        
        logger.info("E-mail - From: " + msg['From'])
        logger.info("E-mail - To: " + msg['To'])
        logger.info("E-mail - Body: " + text)
        
        smtp = smtplib.SMTP()   
        smtp.connect(self.server)   
        smtp.sendmail(msg['From'], self.to_list, msg.as_string())   
        smtp.quit()
Example #12
0
def send_email(subject=None, message=None, from_addr=None, to_addr=None):
    '''
    Send am email via SMTP server.
    This will not prompt for login if you are alread on the internal network.
    '''
    import os
    import getpass
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart

    users_email=getpass.getuser()+'@stsci.edu'

    if not subject:
        subject='Message from %s'%(__file__)
    if not message:
        message='You forgot to put a message into me'
    if not from_addr:
        from_addr=users_email
    if not to_addr:
        to_addr=users_email

    svr_addr='smtp.stsci.edu'
    msg = MIMEMultipart()
    msg['Subject']=subject
    msg['From']=from_addr
    msg['To']=to_addr
    msg.attach(MIMEText(message))
    s = smtplib.SMTP(svr_addr)
    s.sendmail(from_addr, to_addr, msg.as_string())
    s.quit()
    print('\nEmail sent to %s \n' %(from_addr))
Example #13
0
    def sendEmail(self, recipients, body, subject, files=None):
        print "sendEmail"
        try:

            s = smtplib.SMTP('smtp.relay.com')
            s.set_debuglevel(1)
            if files:
                msg = MIMEMultipart()
                msg.attach(MIMEText(body))
                with open(files, 'rb') as f:
                    part = MIMEApplication(f.read())
                    part.add_header('Content-Disposition', 'attachment', filename="%s" % files)
                    msg.attach(part)
            else:
                msg = MIMEText(body)
            sender = '*****@*****.**'
            msg['Subject'] = subject
            msg['From'] = sender
            msg['To'] = ", ".join(recipients)

            s.sendmail(sender, recipients, msg.as_string())
            s.close()

        except smtplib.SMTPException as e:
            print "error: %s" % e
Example #14
0
def send_email(gmail_user, gmail_pwd, FROM, TO, SUBJECT, TEXT):
    """Send an HTML email with a Gmail account"""
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText

    """START GMAIL settings"""
    SERVER = "smtp.gmail.com"
    PORT = 587  # Google says 465 works too

    """START Message settings"""
    message = MIMEMultipart("alternative")
    message["Subject"] = SUBJECT
    message["From"] = FROM
    message["To"] = ", ".join(TO)
    html = "<html><head></head><body>" + TEXT + "</body></html>"  # We add here HTML wrapping tags
    part = MIMEText(html, "html")
    message.attach(part)

    try:
        server = smtplib.SMTP(SERVER, PORT)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message.as_string())
        server.close()
        # At this point, the email has been sent successfully!
    except:
        raise
Example #15
0
def send_email(request):

    ''' View to send reciept email to a user when they check out '''

    ''' TODO: Dead code for now, integrate with template output in future '''

    if request.method == 'POST':
        auction_user = AuctionUser.objects.get(id=user_id)
        auction = Auction.objects.get(id=auction_id)

        msg = MIMEMultipart()
        msg['Subject'] = "Reciept from {}".format(str(auction.name))
        msg['From'] = settings.DJAUCTION_SMTP_USER
        msg['To'] = auction_user.email
        msg_text = ''
        mime_text = MIMEText(msg_text, 'plain')
        msg.attach(mime_text)

        server = smtplib.SMTP(settings.DJAUCTION_SMTP_SERVER, settings.DJAUCTION_SMTP_PORT)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(settings.DJAUCTION_SMTP_USER, settings.DJAUCTION_SMTP_PASS)
        server.sendmail(settings.DJAUCTION_SMTP_USER, auction_user.email, msg.as_string())
        server.close()
        return HttpResponseRedirect(reverse(view_user, args=(auction_user.id,auction.id)))
Example #16
0
 def test_multipart(self):
   # Text first
   msg = MIMEMultipart('alternative')
   msg['Subject'] = 'subject (issue%s)' % self.issue.key.id()
   msg['From'] = '*****@*****.**'
   msg.attach(MIMEText('body', 'plain'))
   msg.attach(MIMEText('ignore', 'html'))
   views._process_incoming_mail(msg.as_string(), '*****@*****.**')
   imsg = models.Message.query(ancestor=self.issue.key).get()
   self.assertEqual(imsg.text, 'body')
   imsg.key.delete()
   # HTML first
   msg = MIMEMultipart('alternative')
   msg['Subject'] = 'subject (issue%s)' % self.issue.key.id()
   msg['From'] = '*****@*****.**'
   msg.attach(MIMEText('ignore', 'html'))
   msg.attach(MIMEText('body', 'plain'))
   views._process_incoming_mail(msg.as_string(), '*****@*****.**')
   imsg = models.Message.query(ancestor=self.issue.key).get()
   self.assertEqual(imsg.text, 'body')
   imsg.key.delete()
   # no text at all
   msg = MIMEMultipart('alternative')
   msg['Subject'] = 'subject (issue%s)' % self.issue.key.id()
   msg['From'] = '*****@*****.**'
   msg.attach(MIMEText('ignore', 'html'))
   self.assertRaises(views.InvalidIncomingEmailError,
                     views._process_incoming_mail, msg.as_string(),
                     '*****@*****.**')
Example #17
0
def mail(mail_from, mail_password, mail_to, content, fpath_list):			# 将多个文件发送至多个接收邮箱
	mail_server = mail_server_check(mail_from)			# 确定发送邮箱的smtp服务地址
	if mail_server:			# 确认发送邮箱的smtp地址
		msg = MIMEMultipart()			# 构建邮件
		msg['Subject'] = Header(u'双犬:[RR]随机用户最后登录时间', 'utf-8')			# 邮件标题
		msg['From'] = mail_from			# 邮件发送地址
		msg['To'] = ",".join(mail_to)			# 邮件接收地址

		text_part = MIMEText(content, 'plain', 'utf-8')			# 构建以content变量(完成状态)为基础的正文部分
		msg.attach(text_part)			# 将正文部分补充至邮件中

		for file_each in fpath_list:			# 对附件列表进行遍历
			f = open(file_each, "rb")			# 以二进制模式打开将作为附件的文件
			file_content = f.read()			# 读取文件内容
			f.close()			# 关闭文件
			file_part = MIMEApplication(file_content)			# 构建附件部分
			file_part.add_header('Content-Disposition', 'attachment', filename = file_each)			# 添加附件头信息,以扩展名决定对方的文件打开方式
			msg.attach(file_part)			# 将附件补充至邮件中
		try:			# 尝试发送邮件
			smtp = smtplib.SMTP(mail_server, 25)			# 以25端口构建smtp服务
			smtp.ehlo()			# 确认smtp服务
			smtp.starttls()			# 创建TLS连接
			smtp.ehlo()			# 再次确认smtp服务
			smtp.login(mail_from, mail_password)			# 登录发送邮箱
			smtp.sendmail(mail_from, mail_to, msg.as_string())			# 发送邮件
			smtp.quit()			# 注销邮箱,退出smtp服务
			return u"通知/输出已放出"			# 报告通知已经发出
		except Exception as ee:			# 邮件发送失败
			return u"对于" +each_to + u"的通知放出失败:" + str(ee)			# 报告邮件发送失败及原因
Example #18
0
	def send(self):
		
		msg = MIMEMultipart()
		
#		msg['MIME-Version']="1.0"
#		msg['Content-Type'] = "text/plain;charset=utf-8"
		msg['Content-Transfer-Encoding'] = "quoted-printable"

		msg['Subject'] = Header(self.subject, 'utf-8')
		msg['From'] = self.sender
		msg['To'] = ','.join(self.recipients)
		if self.CC:
			msg['Cc'] = ','.join(self.CC)
		msg.attach(MIMEText(self.body, 'plain', 'utf-8'))
		
		if self.replyto:
			msg.add_header('reply-to', self.replyto)

		for attachment in self.attachments:
#			if msg.has_key('Content-Type'):
#				del msg['Content-Type']
			msg.attach(attachment.part)
		
		s = smtplib.SMTP('localhost')
		
		recipients = set(self.recipients)
		recipients.update(set(self.CC))
		recipients.update(set(self.BCC))
		
		s.sendmail(self.sender, list(recipients), msg.as_string())
		s.quit()
		
		return list(recipients)
Example #19
0
    def attach(self, payload):
        """
        Add the C{payload} to the current payload list.

        Also prevent from adding payloads with wrong Content-Type and from
        exceeding a maximum of 2 payloads.

        :param payload: The payload to be attached.
        :type payload: email.message.Message
        """
        # first payload's content type must be equal to the protocol parameter
        # given on object creation
        if len(self._payload) == 0:
            if payload.get_content_type() != self.get_param('protocol'):
                raise errors.MultipartConversionError(
                    'Wrong content type.')
        # second payload is always application/octet-stream
        if len(self._payload) == 1:
            if payload.get_content_type() != 'application/octet-stream':
                raise errors.MultipartConversionError(
                    'Wrong content type %s.' % payload.get_content_type)
        # prevent from adding more payloads
        if len(self._payload) == 2:
            raise errors.MultipartConversionError(
                'Cannot have more than two subparts.')
        MIMEMultipart.attach(self, payload)
def send_email(subject, message, boarding_pass=None, email=None):
  if not config["SEND_EMAIL"] or not config["SEND_ADMIN_EMAIL"]: return

  if email is not None:
    config["EMAIL_TO"] = email

  dlog("Sending email to:" + config["EMAIL_TO"])
  for to in [string.strip(s) for s in string.split(config["EMAIL_TO"], ',')]:
    try:
      smtp = smtplib.SMTP(config["SMTP_SERVER"], config["SMTP_PORT"])
      smtp.ehlo()
      if config["SMTP_USE_TLS"]:
        smtp.starttls()
      smtp.ehlo()
      if config["SMTP_AUTH"]:
        smtp.login(config["SMTP_USER"], config["SMTP_PASSWORD"])
      print 'Sending mail to %s.' % to
      msg = MIMEMultipart('mixed')
      msg['Subject'] = subject
      msg['To'] = to
      msg['From'] = config["EMAIL_FROM"]
      msg.attach(MIMEText(message, 'plain'))
      if boarding_pass:
        msg_bp = MIMEText(boarding_pass, 'html')
        msg_bp.add_header('content-disposition', 'attachment', filename='boarding_pass.html')
        msg.attach(msg_bp)
      smtp.sendmail(config["EMAIL_FROM"], to, msg.as_string())

      print 'Email sent successfully.'
      smtp.close()
    except Exception, e:
      print 'Error sending email!'
      raise e
def eMailCSV(fName):
#This allows the uset to automatically send an e-mail containing the CSV file via e-mail
    send_from = "From_Email"
    send_to = "To_Email"
    subject = "Email_Subject"
    header = "To: To_Email\n From: From_Email\n Subject: Email_Subject\n\n\n"
    text = "Email_Text"
    eServer = "email.server.ext"
    ePort = portNumber
    
    msg = MIMEMultipart()
    msg['From']=send_from
    msg['To'] = send_to
    msg['Date'] =formatdate(localtime=True)
    msg['Subject'] = subject
    msg.attach(MIMEText(text))
    
    with open(fName, "rb") as fil:
        msg.attach(MIMEApplication(
            fil.read(),
            Content_Disposition='attachment; filename="%s"' % basename(fName),
            Name=basename(fName)
        ))

    smtp = smtplib.SMTP(eServer,ePort)
    smtp.ehlo()
    #smtp.start_ssl()
    smtp.starttls()
    smtp.ehlo
    smtp.login('Login_Name', 'Login_Password')
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
Example #22
0
    def send(self):
        msg = MIMEMultipart()   
        msg['From'] = self.sender  
        msg['To'] = ';'.join(self.to_list)
        msg['Cc'] = ';'.join(self.cc_list)
        msg['Bcc'] = ';'.join(self.bcc_list)
        msg['Subject'] = self.subject   
        msg.attach(MIMEText(self.body,_charset='utf-8'))

        self.l.log("E-mail - Server: " + self.server)        
        self.l.log("E-mail - From: " + msg['From'])
        self.l.log("E-mail - To: " + msg['To'])
        self.l.log("E-mail - Cc: " + msg['Cc'])
        self.l.log("E-mail - Bcc: " + msg['Bcc'])
        self.l.log("E-mail - Subject: " + msg['Subject'])
        self.l.log("E-mail - Body: " + self.body)
        
        try:
            smtp = smtplib.SMTP()   
            smtp.connect(self.server)   
            address = [i for f in ('To', 'Cc', 'Bcc') if msg[f] for i in msg[f].split(',')]
            smtp.sendmail(msg['From'], address, msg.as_string())   
            smtp.quit()
            self.l.log('Email send successfully.')
        except Exception,e:
            self.l.log('Error: %s' % e)
Example #23
0
  def test_get_activities_extra_fetches_fail(self):
    """Sometimes the extras fetches return errors. Ignore that."""
    self.init()

    batch = MIMEMultipart()
    for i in range(3):
      msg = Message()
      msg.set_payload('HTTP/1.1 500 Foo Bar\n\r\n\r\n')
      msg['Content-ID'] = '<response-abc+%d>' % (i + 1)
      batch.attach(msg)

    # as_string() must be called before get_boundary() to generate the
    # boundaries between parts, but can't be called again, so we capture the
    # result.
    batch_str = batch.as_string()

    self.auth_entity.http = lambda: http.HttpMockSequence(
      [({'status': '200'}, json.dumps({'items': [ACTIVITY_GP_EXTRAS]})),
       ({'status': '200',
         'content-type': 'multipart/mixed; boundary="%s"' % batch.get_boundary()},
        batch_str),
       ])

    cache = util.CacheDict()
    self.assert_equals([ACTIVITY_AS], self.googleplus.get_activities(
        fetch_replies=True, fetch_likes=True, fetch_shares=True, cache=cache))
    for prefix in 'AGC ', 'AGL ', 'AGS ':
      self.assertNotIn(prefix + '001', cache)
Example #24
0
def send_mail(body):
    import smtplib

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

    # me == my email address
    # you == recipient's email address
    me = "*****@*****.**"
    you = "*****@*****.**"

    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "You solved it!"
    msg['From'] = me
    msg['To'] = you

    # Record the MIME types of both parts - text/plain and text/html.
    email_text = MIMEText(body.decode(), 'html')

    # Attach parts into message container.
    msg.attach(email_text)

    # Send the message via local SMTP server.
    s = smtplib.SMTP('smtp.googlemail.com')
    s.starttls()
    s.login("*****@*****.**", "ValentinTagsCommit")
    # sendmail function takes 3 arguments: sender's address, recipient's address
    # and message to send - here it is sent as one string.
    s.sendmail(me, you, msg.as_string())
    s.quit()
Example #25
0
    def send(self,file='', dest='*****@*****.**'):
        sender = '*****@*****.**'
        receivers = [dest]

        try:
            cli = smtplib.SMTP('smtp.gmail.com', 587)
            cli.ehlo()
            cli.starttls()
            cli.login("*****@*****.**", "konnichiwa")
            msg = MIMEMultipart()
            msg['From'] = "Sala Tecnica"
            msg['Subject'] = "Email Autogenerado - Mantto. Aircon"
            msg.attach(MIMEText("Se adjunta un archivo con el resultado de las comprobaciones "
                                "del Mantenimiento Mensual Aircon \n para mejor visualizacion de los datos"
                                " abrir el archivo con Excel"))

            ctype, encoding = mimetypes.guess_type(file)
            if ctype is None or encoding is not None:
                ctype = "application/octet-stream"

            maintype, subtype = ctype.split("/", 1)

            if maintype == "text":
                fp = open(file)
                # Note: we should handle calculating the charset
                attachment = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            attachment.add_header("Content-Disposition", "attachment", filename=basename(file))
            msg.attach(attachment)


            cli.sendmail(sender,receivers,msg.as_string())

        except (socket.gaierror, socket.error, socket.herror, smtplib.SMTPException) as e:
            print (e)
Example #26
0
def send(subject, text, sender=SENDER, recipients=[RECIPIENT], attachments={}, smtp_host=SMTP_HOST, encoding=ENCODING):
    # encode all strings in binary strings
    subject = _binary(subject)
    text = _binary(text)
    sender = _binary(sender)
    if not isinstance(recipients, list):
        recipients = [recipients]
    recipients = _binary(recipients)
    # build the message
    message = MIMEMultipart()
    message['Subject'] = subject
    message['From'] = sender
    message['To'] = ', '.join(recipients)
    # attach text part
    message.attach(MIMEText(text, _charset=encoding))
    # attach attachments if any
    for name,filename in attachments.items():
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(filename,"rb").read())
        encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % name)
        message.attach(part)
    smtp = smtplib.SMTP(smtp_host)
    smtp.sendmail(sender, recipients, message.as_string())
    smtp.quit()
Example #27
0
def test_send_mail(pict=None):
    try:
        host = '213.186.33.20'  # ssl.ovh.net
        COMMASPACE = ', '
        # Create the container (outer) email message.
        msg = MIMEMultipart()
        msg['Subject'] = 'Hello from the bird Feeder'
        mail_sender = '*****@*****.**'
        mail_recipients = ['*****@*****.**', '*****@*****.**', '*****@*****.**']
        msg['From'] = mail_sender
        msg['To'] = COMMASPACE.join(mail_recipients)
        msg.preamble = 'Our family reunion'

        # text part of the message
        fp = open('text.txt', 'rb')
        # Create a text/plain message
        mt = MIMEText(fp.read())
        fp.close()
        msg.attach(mt)
        # image part of the message
        fp = open(pict, 'rb')
        img = MIMEImage(fp.read())
        fp.close()
        msg.attach(img)
        # actuals sending
        server = smtplib.SMTP(host)
        server.login("*****@*****.**", "anna2004")
        server.sendmail(mail_sender, mail_recipients, msg.as_string())
        server.quit()

    except SMTPAuthenticationError as e:
        print(e.smtp_error, e.smtp_code)
Example #28
0
def run():
    input('Welcome to the email tool! (press anything to continue)')
    answer = ''
    while answer != 'p' and answer != 'u' and answer != 'e':
        answer = input('Would you like to print .csv file, or find the union of two email lists (p/u/e)?')
    if answer == 'p':
        s = ''
        l = readCSV(input('Drag .csv file into terminal: '), input('Number of row to be printed: '))
        for i in range(1, len(l)):
            s = s + ', ' + l[i]
        s = l[0] + s
        print(s)
    elif answer == 'u':
        l1 = question(1)
        l2 = question(2)
        l1 = set(l1)
        l2 = set(l2)
        l = list(l1.union(l2))
        s = ''
        for i in range(len(l) - 1):
            s = s + l[i] + ', '
        s = s + l[-1]
        a = 'w'
        while a != 'c' and a != 'p':
            a = input('Found ' + str(len(l)) + ' unique emails. Print or save as .csv? (p/c): ')
        if a == 'p':
            print('\nThe Combined List-\n' + s)
            again()
        else:
            fileName = input("Enter the filename for the .csv (don't include .csv): ")
            fileName = fileName + '.csv'
            directory = input('Drag folder for file into terminal: ')
            directory = directory.replace(' ', '')
            with open(directory + '/' + fileName, 'w') as newFile:
                writer = csv.writer(newFile)
                for i in l:
                    writer.writerow([i])
            input('File created. Thanks for using the email tool!')
            again()
    else:
        send = ''
        while send != 'y' and send != 'n':
            send = input('Send Email? (y/n) ')
        if send == 'y':
            import smtplib
            from email.mime.multipart import MIMEMultipart
            from email.mime.text import MIMEText
            from secrets import email, password


            from_addr= email
            subject = input('subject: ')
            body = input('body: ')
            recipients = input('to (if all, "all"): ')
            if recipients == 'all':
                recipients = l
            else:
                recipients = recipients.split(',')

            mail = smtplib.SMTP('smtp.gmail.com',587)
            mail.ehlo()
            mail.starttls()
            mail.login(email, password)
            
            for to_addr in recipients:
                msg = MIMEMultipart()
                msg['From']=from_addr
                msg['To']=" ,".join(to_addr)
                msg['subject']= subject

                msg.attach(MIMEText(body,'plain'))

                text = msg.as_string()
                mail.sendmail(from_addr,to_addr,text)

            mail.quit()
            again()
<html>
<head></head>

<body>

<p>
<br>
<br>
</p>
</html>

"""
table_html = open("table_html.html","r")
attach_body = MIMEText(html_body.format(result_table=table_html.read()),"html")
msg.attach(attach_body)
table_html.close()

my_file1 = "test_data_stats.csv"

fp1 = open(my_file1,'rb')
attachment1 = MIMEBase("text","csv")
attachment1.set_payload(fp1.read())
attachment1.add_header("Content-Disposition", "attachment", filename=my_file1)
fp1.close()
encoders.encode_base64(attachment1)
msg.attach(attachment1)

my_file2 = "ref_data_stats.csv"

fp2 = open(my_file2,'rb')
Example #30
0
    def setMultMail(self, listReceiveUser, sSubject, sContent):
        if (len(listReceiveUser) == 0):
            return {"code": 0, "msg": "no content"}

        if (self.sSmtpHost is None):
            return {"code": 0, "msg": "smtp host is None"}

        if (self.sLoginUser is None or self.sLoginPass is None):
            return {"code": 0, "msg": "user or password is None"}

        if (sSubject is None or sContent is None):
            return {
                "code": 0,
                "msg": "subject or content is None",
                "data": {
                    "subject": len(sSubject),
                    "content": len(sContent)
                }
            }

        sFromUser = "******" % self.sLoginUser  # 发件人
        sFileName1 = '1.JPG'
        sFileName2 = 'vim.png'

        # MIMEMultipart 我理解为附件的容器
        multMsg = MIMEMultipart()

        # 邮件内容部分(html)
        htmlMsg = MIMEText(_text=sContent, _subtype='html', _charset='utf-8')

        # 附件部分
        f = open(sFileName1, 'rb')
        imgMsg = MIMEApplication(f.read())
        imgMsg.add_header('Content-Disposition',
                          'attachment',
                          filename=sFileName1)
        f.close()

        # 附件部分
        f = open(sFileName2, 'rb')
        imgMsg2 = MIMEApplication(f.read())
        imgMsg2.add_header('Content-Disposition',
                           'attachment',
                           filename=sFileName2)
        f.close()

        # 将各个部分附加到容器中
        multMsg.attach(htmlMsg)
        multMsg.attach(imgMsg)
        multMsg.attach(imgMsg2)

        # 设置邮件的:标题/发件人/收件人
        multMsg["Subject"] = sSubject
        multMsg["From"] = sFromUser
        multMsg["To"] = ";".join(listReceiveUser)

        # 发送邮件
        try:
            smtp = smtplib.SMTP()
            smtp.connect(host=self.sSmtpHost)
            smtp.login(user=self.sLoginUser, password=self.sLoginPass)
            smtp.set_debuglevel(self.bDebugLevel)
            smtp.sendmail(from_addr=sFromUser,
                          to_addrs=listReceiveUser,
                          msg=multMsg.as_string())
            smtp.quit()
            return {"code": 200, "msg": "success"}
        except Exception as e:
            print(e)
        finally:
            smtp.close()
Example #31
0
	def sendMailMessage(self, xMailMessage):
		COMMASPACE = ', '

		if dbg:
			print("PyMailSMTPService sendMailMessage", file=dbgout)
		recipients = xMailMessage.getRecipients()
		sendermail = xMailMessage.SenderAddress
		sendername = xMailMessage.SenderName
		subject = xMailMessage.Subject
		ccrecipients = xMailMessage.getCcRecipients()
		bccrecipients = xMailMessage.getBccRecipients()
		if dbg:
			print("PyMailSMTPService subject: " + subject, file=dbgout)
			print("PyMailSMTPService from:  " + sendername, file=dbgout)
			print("PyMailSMTPService from:  " + sendermail, file=dbgout)
			print("PyMailSMTPService send to: %s" % (recipients,), file=dbgout)

		attachments = xMailMessage.getAttachments()

		textmsg = Message()

		content = xMailMessage.Body
		flavors = content.getTransferDataFlavors()
		if dbg:
			print("PyMailSMTPService flavors len: %d" % (len(flavors),), file=dbgout)

		#Use first flavor that's sane for an email body
		for flavor in flavors:
			if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find('text/plain') != -1:
				if dbg:
					print("PyMailSMTPService mimetype is: " + flavor.MimeType, file=dbgout)
				textbody = content.getTransferData(flavor)

				if len(textbody):
					mimeEncoding = re.sub("charset=.*", "charset=UTF-8", flavor.MimeType)
					if mimeEncoding.find('charset=UTF-8') == -1:
						mimeEncoding = mimeEncoding + "; charset=UTF-8"
					textmsg['Content-Type'] = mimeEncoding
					textmsg['MIME-Version'] = '1.0'

					try:
						#it's a string, get it as utf-8 bytes
						textbody = textbody.encode('utf-8')
					except:
						#it's a bytesequence, get raw bytes
						textbody = textbody.value
					if sys.version >= '3':
						if sys.version_info.minor < 3 or (sys.version_info.minor == 3 and sys.version_info.micro <= 1):
							#http://stackoverflow.com/questions/9403265/how-do-i-use-python-3-2-email-module-to-send-unicode-messages-encoded-in-utf-8-w
							#see http://bugs.python.org/16564, etc. basically it now *seems* to be all ok
							#in python 3.3.2 onwards, but a little busted in 3.3.0

							textbody = textbody.decode('iso8859-1')
						else:
							textbody = textbody.decode('utf-8')
						c = Charset('utf-8')
						c.body_encoding = QP
						textmsg.set_payload(textbody, c)
					else:
						textmsg.set_payload(textbody)

				break

		if (len(attachments)):
			msg = MIMEMultipart()
			msg.epilogue = ''
			msg.attach(textmsg)
		else:
			msg = textmsg

		hdr = Header(sendername, 'utf-8')
		hdr.append('<'+sendermail+'>','us-ascii')
		msg['Subject'] = subject
		msg['From'] = hdr
		msg['To'] = COMMASPACE.join(recipients)
		if len(ccrecipients):
			msg['Cc'] = COMMASPACE.join(ccrecipients)
		if xMailMessage.ReplyToAddress != '':
			msg['Reply-To'] = xMailMessage.ReplyToAddress

		mailerstring = "LibreOffice via Caolan's mailmerge component"
		try:
			ctx = uno.getComponentContext()
			aConfigProvider = ctx.ServiceManager.createInstance("com.sun.star.configuration.ConfigurationProvider")
			prop = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
			prop.Name = "nodepath"
			prop.Value = "/org.openoffice.Setup/Product"
			aSettings = aConfigProvider.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess",
				(prop,))
			mailerstring = aSettings.getByName("ooName") + " " + \
				aSettings.getByName("ooSetupVersion") + " via Caolan's mailmerge component"
		except:
			pass

		msg['X-Mailer'] = mailerstring
		msg['Date'] = formatdate(localtime=True)

		for attachment in attachments:
			content = attachment.Data
			flavors = content.getTransferDataFlavors()
			flavor = flavors[0]
			ctype = flavor.MimeType
			maintype, subtype = ctype.split('/', 1)
			msgattachment = MIMEBase(maintype, subtype)
			data = content.getTransferData(flavor)
			msgattachment.set_payload(data.value)
			encode_base64(msgattachment)
			fname = attachment.ReadableName
			try:
				msgattachment.add_header('Content-Disposition', 'attachment', \
					filename=fname)
			except:
				msgattachment.add_header('Content-Disposition', 'attachment', \
					filename=('utf-8','',fname))
			if dbg:
				print(("PyMailSMTPService attachmentheader: ", str(msgattachment)), file=dbgout)

			msg.attach(msgattachment)

		uniquer = {}
		for key in recipients:
			uniquer[key] = True
		if len(ccrecipients):
			for key in ccrecipients:
				uniquer[key] = True
		if len(bccrecipients):
			for key in bccrecipients:
				uniquer[key] = True
		truerecipients = uniquer.keys()

		if dbg:
			print(("PyMailSMTPService recipients are: ", truerecipients), file=dbgout)

		self.server.sendmail(sendermail, truerecipients, msg.as_string())
Example #32
0
import smtplib
import random
import string
import sys

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

if(len(sys.argv)!=3) :
    sys.exit("Argumentos inválidos")

fromaddr = "*****@*****.**"
toaddr = sys.argv[1]

msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "FileSystem - Código de Validação"
 
body = "Insira este código na aplicação, para ter acesso ao FileSystem:\n" + sys.argv[2]

msg.attach(MIMEText(body, 'plain'))
 
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "Escapes-")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

webbrowser.open('http://localhost:12345')
# mail_password = '******'  # 授权码
# sender = "*****@*****.**"
# receivers = input('输入对方的邮箱:')

msgRoot = MIMEMultipart('related')  # 设置邮件为多文格式
msgRoot['From'] = Header("一位不愿透露姓名的某某", 'utf-8')
msgRoot['To'] = receivers
subject = '一位不愿透露姓名的某某'
msgRoot['Subject'] = Header(subject, 'utf-8')

mail_msg = """
罗罗诺亚·索隆:<br>
<p><img src="cid:image1"></p>
"""
msgtext = MIMEText(mail_msg, 'html', 'utf-8')
msgRoot.attach(msgtext)

# 指定图片为当前目录
path = r'E:\PyCharmp\PycharmProjects\爬虫\爬虫及算法\小程序\picture\3.jpg'
fp = open(path, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

try:
    smtp = smtplib.SMTP(mail_host, 25)
    smtp.login(mail_user, mail_password)
    smtp.sendmail(sender, receivers, msgRoot.as_string())
Example #34
0
subject = "System Reports "
body = "This is an email with attachment sent from Python"
sender_email = "*****@*****.**"
receiver_email = "*****@*****.**"
password = "******"

# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach(MIMEText(body, "plain"))

filename = "employee.pdf"  # In same directory as script

# Open PDF file in binary mode
with open(filename, "rb") as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode file in ASCII characters to send by email
encoders.encode_base64(part)

# Add header as key/value pair to attachment part
part.add_header(
Example #35
0
    df.sort_values(by='Revision Date', inplace=True, ascending=False)
    filtered_df = df[df['Revision Date'] >= date]
    filtered_df = filtered_df.drop(columns=['Shortage Status', 'id'])
    return filtered_df


MASTER_URL = 'https://www.ashp.org/Drug-Shortages/Current-Shortages/Drug-Shortages-List?page=All'
today = datetime.now().strftime('%Y-%m-%d')
today_updates = get_updates(MASTER_URL, today)
# print(today_updates)


s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(config.username, config.password)
message = MIMEMultipart()
message['Subject'] = 'Drug Shortage update for ' + today
message['From'] = '*****@*****.**'
html = """\
<html>
    <head></head>
    <body>
        {0}
    </body>
</html>
""".format(today_updates.to_html(index=False).replace('border="1"', 'border="0"'))
part1 = MIMEText(html, 'html')
message.attach(part1)
s.sendmail('*****@*****.**', '*****@*****.**', message.as_string())
s.quit()
Example #36
0
def register_recovery():
    data = request.get_json()
    found_user = Admin.query.filter_by(email=data["email"]).filter_by(first_name=data["first_name"]).filter_by(
        last_name=data["last_name"]).filter_by(username=data["username"]).first()

    if found_user is not None:
        found_user.recovery_link = encrypt_credentials(data["email"])
        db.session.add(found_user)
        db.session.commit()

        href_link = f"http://0.0.0.0:4001/admin/users/recovery/{found_user.recovery_link}"

        port = os.environ["EMAIL_PORT"]
        smtp_server = os.environ["EMAIL_SERVER"]
        sender = os.environ["EMAIL_SENDER"]
        receiver = os.environ["EMAIL_RECEIVER"]
        password = os.environ["EMAIL_PASSWORD"]

        message = MIMEMultipart("alternative")
        receiver = data["email"]
        message["Subject"] = "Recover Managem Account"
        message["From"] = sender
        message["To"] = receiver
        text = f'Hi {data["first_name"]},\n\n \
            Visit the link below to reset your login credentials for the Managem portal associated with mimspainting.com:\n\n \
              {href_link}\n\n\
            Best regards,\n \
            Mims Family Painting'
        html = """\
        <html>
            <head>
            </head>
            <body
              style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif;
              border: 20px solid black;
              box-sizing: border-box;
              max-width: 680px;
              margin: 0 auto;
              color: black;
            ">
              <div style="padding: 2.5rem; background: #faf8f4; box-sizing: border-box;">
                <img
                  style="
                    width: 80%;
                    background: rgba(141, 141, 141, 0.5);
                    border: black solid 4px;
                    margin: 0 auto 2rem auto;
                    display: block;
                    box-sizing: border-box;
                    padding: 8px;
                  "
                  src="cid:image1"
                  alt="Mims Family Painting"
                />
                <p style="margin: 0 0 1.25rem 0;">Hi {name},</p>
                <p style="margin: 0 0 1.25rem 0;">Visit the link below to reset your login credentials for the Managem portal associated with mimspainting.com:
                </p>
                <p style="margin: 0 0 1.25rem 0;"><a href="{href_link}">Recover account</a></p>
                <p style="margin: 0 0 1.25rem 0;">Best regards,</p>
                <p style="margin: 0;">Mims Family Painting</p>
              </div>
            </body>
        </html>
        """.format(name=data["first_name"], href_link=href_link)
        context = ssl.create_default_context()

        fp = open(os.getcwd() + '/client/public/assets/img/NEWNEWLOGO.png', 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()

        msgImage.add_header('Content-ID', '<image1>')

        part1 = MIMEText(text, "plain")
        part2 = MIMEText(html, "html")

        message.attach(part1)
        message.attach(part2)

        message.attach(msgImage)

        with smtplib.SMTP_SSL(smtp_server, port, context=context) as responder:
            responder.login(sender, password)
            responder.sendmail(sender, receiver, message.as_string())
            responder.close()

        return json.dumps({"message": "A recovery link has been sent to your email. Open it and click the link to recover your account."})

    else:
        return json.dumps({"message": "Double-check your credentials and try again."})
                        composedMessage = MIMEMultipart()
                        composedMessage['Subject'] = 'Requested Information'
                        composedMessage['To'] = eachMap[itemkey]
                        composedMessage['From'] = "*****@*****.**"

                        ctype, encoding = mimetypes.guess_type(filePath)
                        if ctype is None or encoding is not None:
                            ctype = "application/octet-stream"

                        maintype, subtype = ctype.split("/", 1)

                        with open(filePath, newline='') as fp:
                            msg = MIMEBase(maintype, _subtype=subtype)
                            msg.set_payload(fp.read())
                            encoders.encode_base64(msg)

                        msg.add_header("Content-Disposition",
                                       "attachment",
                                       filename='data.txt')
                        composedMessage.attach(msg)

                        mailObject = smtplib.SMTP('smtp.gmail.com', 587)
                        mailObject.starttls()
                        mailObject.login('*****@*****.**',
                                         'Sri13krishna')
                        mailObject.sendmail("*****@*****.**",
                                            "*****@*****.**",
                                            composedMessage.as_string())
                        print('Done sending Mail')
                        os.remove('data.txt')
                        mailObject.close()
Example #38
0
def send_manifest(form_data,
                  port=0,
                  servicename=None,
                  protocolversion=COMPATIBILITY_VERSION,
                  no_default=False):
    '''Replies to the client with matching service for a service.
    
    Args
        form_data   - the postData passed in from the client request
        port        - the port of the old client
        servicename - the name of the service being used
        protocolversion - the version of the AI service RE: handshake
        no_default  - boolean flag to signify whether or not we should hand
                      back the default manifest and profiles if one cannot
                      be matched based on the client criteria.

    Returns
        None
    
    Raises
        None
    
    '''
    # figure out the appropriate path for the AI database,
    # and get service name if necessary.
    # currently service information is stored in a port directory.
    # When the cherrypy webserver new service directories should be
    # separated via service-name only.  Old services will still use
    # port numbers as the separation mechanism.
    path = None
    found_servicename = None
    service = None
    port = str(port)

    if servicename:
        service = AIService(servicename)
        path = service.database_path
    else:
        for name in config.get_all_service_names():
            if config.get_service_port(name) == port:
                found_servicename = name
                service = AIService(name)
                path = service.database_path
                break

    # Check to insure that a valid path was found
    if not path or not os.path.exists(path):
        print 'Content-Type: text/html'  # HTML is following
        print  # blank line, end of headers
        if servicename:
            print '<pre><b>Error</b>:unable to find<i>', servicename + '</i>.'
        else:
            print '<pre><b>Error</b>:unable to find<i>', port + '</i>.'
        print 'Available services are:<p><ol><i>'
        hostname = socket.gethostname()
        for name in config.get_all_service_names():
            port = config.get_service_port(name)
            sys.stdout.write(
                '<a href="http://%s:%d/cgi-bin/'
                'cgi_get_manifest.py?version=%s&service=%s">%s</a><br>\n' %
                (hostname, port, VERSION, name, name))
        print '</i></ol>Please select a service from the above list.'
        return

    if found_servicename:
        servicename = found_servicename

    # load to the AI database
    aisql = AIdb.DB(path)
    aisql.verifyDBStructure()

    # convert the form data into a criteria dictionary
    criteria = dict()
    orig_data = form_data
    while form_data:
        try:
            [key_value, form_data] = form_data.split(';', 1)
        except (ValueError, NameError, TypeError, KeyError):
            key_value = form_data
            form_data = ''
        try:
            [key, value] = key_value.split('=')
            criteria[key] = value
        except (ValueError, NameError, TypeError, KeyError):
            criteria = dict()

    # Generate templating dictionary from criteria
    template_dict = dict()
    for crit in criteria:
        template_dict["AI_" + crit.upper()] = \
                AIdb.formatValue(crit, criteria[crit], units=False)

    # find the appropriate manifest
    try:
        manifest = AIdb.findManifest(criteria, aisql)
    except StandardError as err:
        print 'Content-Type: text/html'  # HTML is following
        print  # blank line, end of headers
        print '<pre><b>Error</b>:findManifest criteria<br>'
        print err, '<br>'
        print '<ol>servicename =', servicename
        print 'port        =', port
        print 'path        =', path
        print 'form_data   =', orig_data
        print 'criteria    =', criteria
        print 'servicename found by port =', found_servicename, '</ol>'
        print '</pre>'
        return

    # check if findManifest() returned a number equal to 0
    # (means we got no manifests back -- thus we serve the default if desired)
    if manifest is None and not no_default:
        manifest = service.get_default_manifest()

    # if we have a manifest to return, prepare its return
    if manifest is not None:
        try:
            # construct the fully qualified filename
            filename = os.path.abspath(
                os.path.join(service.manifest_dir, manifest))
            # open and read the manifest
            with open(filename, 'rb') as mfp:
                manifest_str = mfp.read()
            # maintain compability with older AI client
            if servicename is None or \
                    float(protocolversion) < float(PROFILES_VERSION):
                content_type = mimetypes.types_map.get('.xml', 'text/plain')
                print 'Content-Length:', len(
                    manifest_str)  # Length of the file
                print 'Content-Type:', content_type  # XML is following
                print  # blank line, end of headers
                print manifest_str
                logging.info('Manifest sent from %s.' % filename)
                return

        except OSError as err:
            print 'Content-Type: text/html'  # HTML is following
            print  # blank line, end of headers
            print '<pre>'
            # report the internal error to error_log and requesting client
            sys.stderr.write(_('error:manifest (%s) %s\n') % \
                            (str(manifest), err))
            sys.stdout.write(_('error:manifest (%s) %s\n') % \
                            (str(manifest), err))
            print '</pre>'
            return

    # get AI service image path
    service = AIService(servicename)
    image_dir = service.image.path
    # construct object to contain MIME multipart message
    outermime = MIMEMultipart()
    client_msg = list()  # accumulate message output for AI client

    # If we have a manifest, attach it to the return message
    if manifest is not None:
        # add manifest as attachment
        msg = MIMEText(manifest_str, 'xml')
        # indicate manifest using special name
        msg.add_header('Content-Disposition',
                       'attachment',
                       filename=sc.AI_MANIFEST_ATTACHMENT_NAME)
        outermime.attach(msg)  # add manifest as an attachment

    # search for any profiles matching client criteria
    # formulate database query to profiles table
    q_str = "SELECT DISTINCT name, file FROM " + \
        AIdb.PROFILES_TABLE + " WHERE "
    nvpairs = list()  # accumulate criteria values from post-data
    # for all AI client criteria
    for crit in AIdb.getCriteria(aisql.getQueue(),
                                 table=AIdb.PROFILES_TABLE,
                                 onlyUsed=False):
        if crit not in criteria:
            msgtxt = _("Warning: client criteria \"%s\" not provided in "
                       "request.  Setting value to NULL for profile lookup.") \
                       % crit
            client_msg += [msgtxt]
            logging.warn(msgtxt)
            # fetch only global profiles destined for all clients
            if AIdb.isRangeCriteria(aisql.getQueue(), crit,
                                    AIdb.PROFILES_TABLE):
                nvpairs += ["MIN" + crit + " IS NULL"]
                nvpairs += ["MAX" + crit + " IS NULL"]
            else:
                nvpairs += [crit + " IS NULL"]
            continue

        # prepare criteria value to add to query
        envval = AIdb.sanitizeSQL(criteria[crit])
        if AIdb.isRangeCriteria(aisql.getQueue(), crit, AIdb.PROFILES_TABLE):
            # If no default profiles are requested, then we mustn't allow
            # this criteria to be NULL.  It must match the client's given
            # value for this criteria.
            if no_default:
                if crit == "mac":
                    nvpairs += ["(HEX(MIN" + crit + ")<=HEX(X'" + envval + \
                        "'))"]

                    nvpairs += ["(HEX(MAX" + crit + ")>=HEX(X'" + envval + \
                        "'))"]
                else:
                    nvpairs += ["(MIN" + crit + "<='" + envval + "')"]
                    nvpairs += ["(MAX" + crit + ">='" + envval + "')"]
            else:
                if crit == "mac":
                    nvpairs += [
                        "(MIN" + crit + " IS NULL OR "
                        "HEX(MIN" + crit + ")<=HEX(X'" + envval + "'))"
                    ]
                    nvpairs += [
                        "(MAX" + crit + " IS NULL OR HEX(MAX" + crit +
                        ")>=HEX(X'" + envval + "'))"
                    ]
                else:
                    nvpairs += [
                        "(MIN" + crit + " IS NULL OR MIN" + crit + "<='" +
                        envval + "')"
                    ]
                    nvpairs += [
                        "(MAX" + crit + " IS NULL OR MAX" + crit + ">='" +
                        envval + "')"
                    ]
        else:
            # If no default profiles are requested, then we mustn't allow
            # this criteria to be NULL.  It must match the client's given
            # value for this criteria.
            #
            # Also, since this is a non-range criteria, the value stored
            # in the DB may be a whitespace separated list of single
            # values.  We use a special user-defined function in the
            # determine if the given criteria is in that textual list.
            if no_default:
                if crit == "hostname":
                    nvpairs += ["(match_hostname('" + envval + \
                                "', hostname, 0) == 1)"]
                else:
                    nvpairs += ["(is_in_list('" + crit + "', '" + envval + \
                                "', " + crit + ", 'None') == 1)"]
            else:
                if crit == "hostname":
                    nvpairs += ["( hostname IS NULL OR match_hostname('" + \
                                envval + "', hostname, 0) == 1)"]
                else:
                    nvpairs += ["(" + crit + " IS NULL OR is_in_list('" + \
                                crit + "', '" + envval + "', " + crit + \
                                ", 'None') == 1)"]

    if len(nvpairs) > 0:
        q_str += " AND ".join(nvpairs)

        # issue database query
        logging.info("Profile query: " + q_str)
        query = AIdb.DBrequest(q_str)
        aisql.getQueue().put(query)
        query.waitAns()
        if query.getResponse() is None or len(query.getResponse()) == 0:
            msgtxt = _("No profiles found.")
            client_msg += [msgtxt]
            logging.info(msgtxt)
        else:
            for row in query.getResponse():
                profpath = row['file']
                profname = row['name']
                if profname is None:  # should not happen
                    profname = 'unnamed'
                try:
                    if profpath is None:
                        msgtxt = "Database record error - profile path is " \
                            "empty."
                        client_msg += [msgtxt]
                        logging.error(msgtxt)
                        continue
                    msgtxt = _('Processing profile %s') % profname
                    client_msg += [msgtxt]
                    logging.info(msgtxt)
                    with open(profpath, 'r') as pfp:
                        raw_profile = pfp.read()
                    # do any template variable replacement {{AI_xxx}}
                    tmpl_profile = sc.perform_templating(
                        raw_profile, template_dict)
                    # precautionary validation of profile, logging only
                    sc.validate_profile_string(tmpl_profile,
                                               image_dir,
                                               dtd_validation=True,
                                               warn_if_dtd_missing=True)
                except IOError as err:
                    msgtxt = _("Error:  I/O error: ") + str(err)
                    client_msg += [msgtxt]
                    logging.error(msgtxt)
                    continue
                except OSError:
                    msgtxt = _("Error:  OS error on profile ") + profpath
                    client_msg += [msgtxt]
                    logging.error(msgtxt)
                    continue
                except KeyError:
                    msgtxt = _('Error:  could not find criteria to substitute '
                               'in template: ') + profpath
                    client_msg += [msgtxt]
                    logging.error(msgtxt)
                    logging.error('Profile with template substitution error:' +
                                  raw_profile)
                    continue
                except lxml.etree.XMLSyntaxError as err:
                    # log validation error and proceed
                    msgtxt = _(
                            'Warning:  syntax error found in profile: ') \
                            + profpath
                    client_msg += [msgtxt]
                    logging.error(msgtxt)
                    for error in err.error_log:
                        msgtxt = _('Error:  ') + error.message
                        client_msg += [msgtxt]
                        logging.error(msgtxt)
                    logging.info([
                        _('Profile failing validation:  ') +
                        lxml.etree.tostring(root)
                    ])
                # build MIME message and attach to outer MIME message
                msg = MIMEText(tmpl_profile, 'xml')
                # indicate in header that this is an attachment
                msg.add_header('Content-Disposition',
                               'attachment',
                               filename=profname)
                # attach this profile to the manifest and any other profiles
                outermime.attach(msg)
                msgtxt = _('Parsed and loaded profile: ') + profname
                client_msg += [msgtxt]
                logging.info(msgtxt)

    # any profiles and AI manifest have been attached to MIME message
    # specially format list of messages for display on AI client console
    if client_msg:
        outtxt = ''
        for msgtxt in client_msg:
            msgtxt = _('SC profile locator:') + msgtxt
            outtxt += str(msgtxt) + '\n'
        # add AI client console messages as single plain text attachment
        msg = MIMEText(outtxt, 'plain')  # create MIME message
        outermime.attach(msg)  # attach MIME message to response

    print outermime.as_string()  # send MIME-formatted message
Example #39
0
messages = yaml_contents['messages']
for msg in messages:
  for key in ['to', 'subject', 'contents']:
    check_key('Message with contents: ' + str(msg), msg, key)

  # Make non-list fields lists.
  for field in ['to', 'cc', 'bcc', 'attach']:
    if field in msg and not isinstance(msg[field], list):
      msg[field] = [msg[field]]

  multi_msg = MIMEMultipart()
  multi_msg['From'] = smtp['from']
  multi_msg['To'] = ",".join(msg['to'])
  multi_msg['Subject'] = msg['subject']
  if 'cc' in msg: multi_msg['CC'] = ",".join(msg['cc'])
  multi_msg.attach(MIMEText(msg['contents']))

  if 'attach' in msg:
    for f_name in msg['attach']:
      part = MIMEBase('application', "octet-stream")
      with open(f_name, 'rb') as f: part.set_payload(f.read())
      encode_base64(part)
      part.add_header('Content-Disposition',
          'attachment; filename="' + basename(f_name) + '"')
      multi_msg.attach(part)

  print("Sending message.")
  print("  To: " + ",".join(msg['to']))
  if 'cc' in msg: print("  CC: " + ",".join(msg['cc']))
  if 'bcc' in msg: print("  BCC: " + ",".join(msg['bcc']))
  print("  Subject: " + msg['subject'])
Example #40
0

for i in range(len(names)):
    message = MIMEMultipart()
    message["Subject"] = "Invitation for DJ ACM's Internship Fair"
    message["From"] = from_email
    message["To"] = emails[i]
    html = """<p>Greetings,</p>
    <br>
    <p>&nbsp; &nbsp; &nbsp; &nbsp; Dwarkadas J. Sanghvi's Association of Computing Machinery (ACM ) is a student chapter that helps students by connecting their curriculum to the industry to facilitate a structured path from education to employment. The committee strongly believes in the 'learning by doing' ethos and aims to give the next generation of engineers an opportunity to explore several domains.</p>
    <br>
    <p>&nbsp; &nbsp; &nbsp; &nbsp; This is to bring to your kind notice that DJ ACM is organizing it's annual Internship Fair on the 9th and 10th of April that will be held virtually this year. We are seeking companies that are currently looking to fill both technical and/or non-technical internship positions with individuals having relevant work experience and would be honoured to have your esteemed company on board. We can discuss the job description with your representatives, learn the specific requirements and compile a resume list to allow for efficient filtering. Executives from {company_name} can conduct the interviews of the shortlisted candidates in the aforementioned timeframe. The stipend, which is a necessity, is to be discussed with the selected candidates. Please note that the candidates should not be required to pay any course/training fees during the duration of their internship. {company_name} would receive extensive publicity on our social media handles and banners, posters and standees of the company would be put up during the event to ensure maximum possible reach within the student community.
    </p>
    <br>
    <p>&nbsp; &nbsp; &nbsp; &nbsp; We look forward to a mutually beneficial collaboration. Our team would be happy to coordinate the details or clarify questions. Please reach out to us at {from_email} or {contact_no}. Please do respond at your earliest convenience. </p>
    <br>
    <div style="padding:0;">Thanking you in anticipation,<br>
    {name}<br>
    {position}</div>
    """.format(company_name=names[i], from_email=from_email, name=my_name, position=my_position, contact_no=contact_no)
    content = MIMEText(html, "html")
    message.attach(content)
    context = ssl.create_default_context()
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(message["From"], from_password)
    server.sendmail(message["From"], message["To"], message.as_string())
    server.quit()

    print("sent", i+1)
Example #41
0
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

try:
    email = "<< Enter your email >>"
    password = "******"
    to = "<< Enter sender email >>"
    msg = """ << Email Body >>"""
    message = MIMEMultipart()
    message["From"] = email
    message["To"] = to
    message["Subject"] = "HacktoberFest 2019"
    message.attach(MIMEText(msg, "plain"))
    context = ssl.create_default_context()
    server = smtplib.SMTP("smtp.gmail.com")
    server.starttls()
    server.ehlo()
    server.login(email, password)
    server.sendmail(email, to, message.as_string())
    print('Email have been successfully send')

except Exception as ex:
    print(ex)

finally:
    server.quit()
Example #42
0
    def publishFromHTML(self, prouid, results_html):

        uc = getToolByName(self.context, 'uid_catalog')
        pros = uc(UID=prouid)
        if not pros or len(pros) != 1:
            return []

        pro = pros[0].getObject()

        # HTML written to debug file
        debug_mode = App.config.getConfiguration().debug_mode
        if debug_mode:
            tmp_fn = tempfile.mktemp(suffix=".html")
            logger.debug("Writing HTML for %s to %s" % (pro.Title(), tmp_fn))
            open(tmp_fn, "wb").write(results_html)

        # Create the pdf report (will always be attached to the Order)
        # we must supply the file ourself so that createPdf leaves it alone.
        # This version replaces 'attachment' links; probably not required,
        # so it's repeated below, without these localise_images.
        # cleanup, results_html_for_pdf = self.localise_images(results_html)
        # pdf_fn = tempfile.mktemp(suffix=".pdf")
        # pdf_report = createPdf(htmlreport=results_html_for_pdf, outfile=pdf_fn)
        # for fn in cleanup:
        #     os.remove(fn)

        pdf_fn = tempfile.mktemp(suffix=".pdf")
        pdf_report = createPdf(htmlreport=results_html, outfile=pdf_fn)

        # PDF written to debug file
        if debug_mode:
            logger.debug("Writing PDF for %s to %s" % (pro.Title(), pdf_fn))
        else:
            os.remove(pdf_fn)

        recipients = []

        # Send report to supplier
        supplier_data = self._supplier_data(pro)
        title = encode_header(supplier_data.get('title', ''))
        email = supplier_data.get('email')
        formatted = formataddr((title, email))

        # Create the new mime_msg object
        mime_msg = MIMEMultipart('related')
        mime_msg['Subject'] = self.get_mail_subject(pro)
        # Edit this to change the From address
        lab = pro.bika_setup.laboratory
        mime_msg['From'] = formataddr(
            (encode_header(lab.getName()), lab.getEmailAddress()))

        mime_msg.preamble = 'This is a multi-part MIME message.'
        msg_txt = MIMEText(results_html, _subtype='html')
        mime_msg.attach(msg_txt)
        mime_msg['To'] = formatted

        # Attach the pdf to the email if requested
        if pdf_report:
            attachPdf(mime_msg, pdf_report, pdf_fn)

        msg_string = mime_msg.as_string()

        # content of outgoing email written to debug file
        if debug_mode:
            tmp_fn = tempfile.mktemp(suffix=".email")
            logger.debug("Writing MIME message for %s to %s" %
                         (pro.Title(), tmp_fn))
            open(tmp_fn, "wb").write(msg_string)

        try:
            host = getToolByName(pro, 'MailHost')
            host.send(msg_string, immediate=True)
        except SMTPServerDisconnected as msg:
            logger.warn("SMTPServerDisconnected: %s." % msg)
        except SMTPRecipientsRefused as msg:
            raise WorkflowException(str(msg))

        pro.setDateDispatched(DateTime())
        return [pro]
Example #43
0
#!/usr/bin/env python
# -*- coding=utf-8 -*-

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

sender = "*****@*****.**"
rcpt = "*****@*****.**"
msg = MIMEMultipart(alternatvie)
msg[Subject] = Header("测试发信","utf-8") #组装信头
msg[From] = r"%s <*****@*****.**>" % Header("小吴","utf-8") #使用国际化编码
msg[To] = rcpt

html = open(html.tpl).read() #读取HTML模板
html_part = MIMEText(html,html) #实例化为html部分
html_part.set_charset(utf-8) #设置编码
msg.attach(html_part) #绑定到message里

try:
	s = smtplib.SMTP('smtp.exmail.qq.com') #登录SMTP服务器,发信
	s.login(pywugw,*******)
	s.sendmail(sender,rcpt,msg.as_string())
except Exception,e:
	print e 
Example #44
0
    def _message(self):
        """Creates the email"""
        ascii_attachments = current_app.extensions['mail'].ascii_attachments
        catch_all = current_app.extensions['mail'].catch_all
        encoding = self.charset or 'utf-8'

        attachments = self.attachments or []

        if len(attachments) == 0 and not self.alts:
            # No html content and zero attachments means plain text
            msg = self._mimetext(self.body)
        elif len(attachments) > 0 and not self.alts:
            # No html and at least one attachment means multipart
            msg = MIMEMultipart()
            msg.attach(self._mimetext(self.body))
        else:
            # Anything else
            msg = MIMEMultipart()
            alternative = MIMEMultipart('alternative')
            alternative.attach(self._mimetext(self.body, 'plain'))
            for mimetype, content in self.alts.items():
                alternative.attach(self._mimetext(content, mimetype))
            msg.attach(alternative)

        if self.subject:
            msg['Subject'] = sanitize_subject(force_text(self.subject),
                                              encoding)

        msg['From'] = sanitize_address(self.sender, encoding)
        msg['To'] = ', '.join(
            list(set(sanitize_addresses(self.recipients, encoding,
                                        catch_all))))

        msg['Date'] = formatdate(self.date, localtime=True)
        # see RFC 5322 section 3.6.4.
        msg['Message-ID'] = self.msgId

        if self.cc:
            msg['Cc'] = ', '.join(
                list(set(sanitize_addresses(self.cc, encoding, catch_all))))

        if self.reply_to:
            msg['Reply-To'] = sanitize_address(self.reply_to, encoding)

        if self.extra_headers:
            for k, v in self.extra_headers.items():
                msg[k] = v

        SPACES = re.compile(r'[\s]+', re.UNICODE)
        for attachment in attachments:
            f = MIMEBase(*attachment.content_type.split('/'))
            f.set_payload(attachment.data)
            encode_base64(f)

            filename = attachment.filename
            if filename and ascii_attachments:
                # force filename to ascii
                filename = unicodedata.normalize('NFKD', filename)
                filename = filename.encode('ascii', 'ignore').decode('ascii')
                filename = SPACES.sub(u' ', filename).strip()

            try:
                filename and filename.encode('ascii')
            except UnicodeEncodeError:
                if not PY3:
                    filename = filename.encode('utf8')
                filename = ('UTF8', '', filename)

            f.add_header('Content-Disposition',
                         attachment.disposition,
                         filename=filename)

            for key, value in attachment.headers.items():
                f.add_header(key, value)

            msg.attach(f)
        if message_policy:
            msg.policy = message_policy

        return msg
Example #45
0
#Time between measurements.(Seconds)
ara = 0

#Reciever emails should be added here
receivers = ["*****@*****.**", "*****@*****.**"]

msg = MIMEMultipart()

#Message
message = """
    Troughput datas are ready.
    """
msg['From'] = "Raspberry Pi"
msg['Subject'] = "KPI Data M."

msg.attach(MIMEText(message, 'plain'))

mysql.connector.connect(host='localhost',
                        database='SENSOR',
                        user='******',
                        password='******')

response = subprocess.Popen('speedtest-cli --simple',
                            shell=True,
                            stdout=subprocess.PIPE).stdout.read()


def TPut():
    download = re.findall('Download:\s(.*?)\s', response, re.MULTILINE)
    dwn1 = float(download[0])
Example #46
0
def get_SlotFunction(sc):
    currentDateTime = date.today() + timedelta(days=1)
    Odate = currentDateTime.strftime(
        "%d-%m-%Y")  #Needs to be in the format DD-MM-YYYY
    OdistrictCode = "360"  #Find your district code from the Cowin API Setu
    slotAvailability = False

    #Print Date and District Code
    print("Checking For Date: " + Odate + " and DistrictCode:" + OdistrictCode)

    ##Send email
    senderAddress = ""  #From E-mail address
    senderPassword = ""  #Password
    receiverAddress = ""  #To E-mail address
    #Setup the MIME
    message = MIMEMultipart()
    message['From'] = senderAddress
    message['To'] = receiverAddress
    message[
        'Subject'] = 'ATTENTION: Vaccination Slot Available!'  #The subject line
    #The body and the attachments for the mail
    mailBody = "Hello, Slots have opened up for the 18+ age category in your district.\n"
    response = requests.get(
        "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?district_id="
        + OdistrictCode + "&date=" + Odate,
        headers={
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
        })  #Do not modify the headers
    statusCode = response.status_code
    sessionsDictionary = json.loads(json.dumps(response.json()))
    sessionCount = (len(sessionsDictionary["centers"]))
    for i in range(len(sessionsDictionary["centers"])):
        for j in range(len(sessionsDictionary["centers"][i]["sessions"])):
            if sessionsDictionary["centers"][i]["sessions"][j][
                    "min_age_limit"] == 45 and sessionsDictionary["centers"][
                        i]["sessions"][j]["available_capacity"] > 0:
                mailBody = mailBody + "\n" + sessionsDictionary["centers"][i][
                    "name"] + '\n' + "Date : " + sessionsDictionary["centers"][
                        i]["sessions"][j][
                            "date"] + "\n" + "Available Count : " + str(
                                sessionsDictionary["centers"][i]["sessions"][j]
                                ["available_capacity"]) + '\n\n'
                slotAvailability = True

    if slotAvailability == True:
        #Create SMTP session for sending the mail
        message.attach(MIMEText(mailBody, 'plain'))
        session = smtplib.SMTP('smtp.gmail.com', 587)  #use gmail with port
        session.starttls()  #enable security
        session.login(senderAddress,
                      senderPassword)  #login with mail_id and password
        text = message.as_string()
        session.sendmail(senderAddress, receiverAddress, text)
        session.quit()
        print("Status Code: " + str(statusCode) +
              ". Slots available. Check email for details.")

    else:
        print("Status Code: " + str(statusCode) +
              ". Sorry! No slots available")

    print(
        "------------------------------------------------------------------------------------"
    )

    sch.enter(30, 1, get_SlotFunction, (sc, ))  #Here 30 represents 30 secs.
Example #47
0
    def send(self, recipients, subject="", body="", filename=None):
        msg = MIMEMultipart()
        if not self._username or not self._userpass:
            raise UserInfoError()

        if isinstance(recipients, str):
            recipients = [recipients]

        msg['From'] = self._username
        msg['To'] = self.COMMASPACE.join(recipients)

        if subject == "":
            msg['Subject'] = self._subject
        else:
            msg['Subject'] = subject

        if body == "":
            body = self._body
        else:
            body = MIMEText(body)

        msg.attach(body)

        if filename is not None:
            import os
            import mimetypes

            file_basename = os.path.basename(filename)
            ctype, encoding = mimetypes.guess_type(filename)

            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/')

            if maintype == 'image':
                from email.mime.image import MIMEImage
                with open(filename, 'rb') as fp:
                    part = MIMEImage(fp.read(), _subtype=subtype)
            else:
                from email.mime.base import MIMEBase
                from email import encoders
                with open(filename, 'rb') as fp:
                    part = MIMEBase(maintype, subtype)
                    part.set_payload(fp.read())
                encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment',
                            filename=file_basename)
            msg.attach(part)

        try:
            self._initialize()
            self._sendmail(recipients, msg)
        except smtplib.SMTPAuthenticationError as e:
            print(str(e))
        except smtplib.SMTPConnectError as e:
            print(str(e))
        except smtplib.SMTPServerDisconnected as e:
            print(str(e))
            self._server = None
            self._initialize()
            self._sendmail(recipients, msg)
        except smtplib.SMTPException as e:
            print(str(e))
        else:
            print("Sent mail from %s to %s, Success!!" %
                  (self._username, recipients))
Example #48
0
    def build_email(self,
                    email_from,
                    email_to,
                    subject,
                    body,
                    email_cc=None,
                    email_bcc=None,
                    reply_to=False,
                    attachments=None,
                    message_id=None,
                    references=None,
                    object_id=False,
                    subtype='plain',
                    headers=None,
                    body_alternative=None,
                    subtype_alternative='plain'):
        """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it.

           :param string email_from: sender email address
           :param list email_to: list of recipient addresses (to be joined with commas) 
           :param string subject: email subject (no pre-encoding/quoting necessary)
           :param string body: email body, of the type ``subtype`` (by default, plaintext).
                               If html subtype is used, the message will be automatically converted
                               to plaintext and wrapped in multipart/alternative, unless an explicit
                               ``body_alternative`` version is passed.
           :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative``
           :param string reply_to: optional value of Reply-To header
           :param string object_id: optional tracking identifier, to be included in the message-id for
                                    recognizing replies. Suggested format for object-id is "res_id-model",
                                    e.g. "12345-crm.lead".
           :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'),
                                  must match the format of the ``body`` parameter. Default is 'plain',
                                  making the content part of the mail "text/plain".
           :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain'
                                              or 'html'). Default is 'plain'.
           :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string
                                    containing the bytes of the attachment
           :param list email_cc: optional list of string values for CC header (to be joined with commas)
           :param list email_bcc: optional list of string values for BCC header (to be joined with commas)
           :param dict headers: optional map of headers to set on the outgoing mail (may override the
                                other headers, including Subject, Reply-To, Message-Id, etc.)
           :rtype: email.message.Message (usually MIMEMultipart)
           :return: the new RFC2822 email message
        """
        email_from = email_from or tools.config.get('email_from')
        assert email_from, "You must either provide a sender address explicitly or configure "\
                           "a global sender address in the server configuration or with the "\
                           "--email-from startup parameter."

        # Note: we must force all strings to to 8-bit utf-8 when crafting message,
        #       or use encode_header() for headers, which does it automatically.

        headers = headers or {}  # need valid dict later
        email_cc = email_cc or []
        email_bcc = email_bcc or []
        body = body or u''

        email_body_utf8 = ustr(body).encode('utf-8')
        email_text_part = MIMEText(email_body_utf8,
                                   _subtype=subtype,
                                   _charset='utf-8')
        msg = MIMEMultipart()

        if not message_id:
            if object_id:
                message_id = tools.generate_tracking_message_id(object_id)
            else:
                message_id = make_msgid()
        msg['Message-Id'] = encode_header(message_id)
        if references:
            msg['references'] = encode_header(references)
        msg['Subject'] = encode_header(subject)
        msg['From'] = encode_rfc2822_address_header(email_from)
        del msg['Reply-To']
        if reply_to:
            msg['Reply-To'] = encode_rfc2822_address_header(reply_to)
        else:
            msg['Reply-To'] = msg['From']
        msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to))
        if email_cc:
            msg['Cc'] = encode_rfc2822_address_header(
                COMMASPACE.join(email_cc))
        if email_bcc:
            msg['Bcc'] = encode_rfc2822_address_header(
                COMMASPACE.join(email_bcc))
        msg['Date'] = formatdate()
        # Custom headers may override normal headers or provide additional ones
        for key, value in headers.iteritems():
            msg[ustr(key).encode('utf-8')] = encode_header(value)

        if subtype == 'html' and not body_alternative and html2text:
            # Always provide alternative text body ourselves if possible.
            text_utf8 = tools.html2text(
                email_body_utf8.decode('utf-8')).encode('utf-8')
            alternative_part = MIMEMultipart(_subtype="alternative")
            alternative_part.attach(
                MIMEText(text_utf8, _charset='utf-8', _subtype='plain'))
            alternative_part.attach(email_text_part)
            msg.attach(alternative_part)
        elif body_alternative:
            # Include both alternatives, as specified, within a multipart/alternative part
            alternative_part = MIMEMultipart(_subtype="alternative")
            body_alternative_utf8 = ustr(body_alternative).encode('utf-8')
            alternative_body_part = MIMEText(body_alternative_utf8,
                                             _subtype=subtype_alternative,
                                             _charset='utf-8')
            alternative_part.attach(alternative_body_part)
            alternative_part.attach(email_text_part)
            msg.attach(alternative_part)
        else:
            msg.attach(email_text_part)

        if attachments:
            for (fname, fcontent) in attachments:
                filename_rfc2047 = encode_header_param(fname)
                part = MIMEBase('application', "octet-stream")

                # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail
                # so we fix it by using RFC2047 encoding for the filename instead.
                part.set_param('name', filename_rfc2047)
                part.add_header('Content-Disposition',
                                'attachment',
                                filename=filename_rfc2047)

                part.set_payload(fcontent)
                Encoders.encode_base64(part)
                msg.attach(part)
        return msg
Example #49
0
HOST = "smtp.163.com"
SUBJECT = u"官网业务服务质量周报"
TO = "*****@*****.**"
FROM = "*****@*****.**"

def addimg(src,imgid):
    fp = open(src, 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', imgid)
    return msgImage

msg = MIMEMultipart('related')
msgtext = MIMEText("<font color=red>官网业务周平均延时图表:<br><img src=\"cid:weekly\" border=\"1\"><br>详细内容见附件。</font>","html","utf-8")
msg.attach(msgtext)
msg.attach(addimg("img/weekly.png","weekly"))

attach = MIMEText(open("doc/week_report.xlsx", "rb").read(), "base64", "utf-8")
attach["Content-Type"] = "application/octet-stream"
#attach["Content-Disposition"] = "attachment; filename=\"业务服务质量周报(12周).xlsx\"".decode("utf-8").encode("gb18030")
msg.attach(attach)

msg['Subject'] = SUBJECT
msg['From']=FROM
msg['To']=TO
try:
    server = smtplib.SMTP()
    server.connect(HOST,"25")
    # server.starttls()
    server.login("*****@*****.**","&&&&&&&&")
Example #50
0
def spoof(mail_from,
          to_email,
          subject,
          content,
          mime_from=None,
          mime_from1=None,
          mime_from2=None,
          sender=None,
          helo=None,
          filename=None):
    from_domain = get_email_domain(mail_from)
    if from_domain is None:
        logger.warn("Invalid FROM domain: " + mail_from)

    to_domain = get_email_domain(to_email)
    if to_domain is None:
        logger.warn("Invalid TO domain: " + to_email)

    mx_domain = get_mx(to_domain)
    # print("mx_domain:",mx_domain)
    if mx_domain is None:
        logger.warn("Can't not resolve mx: " + to_domain)

    # start
    smtp = Smtp(mx_domain)

    if not helo:
        helo = from_domain
    if helo:
        smtp.cmd("HELO " + helo)
    else:
        smtp.cmd("HELO " + 'test1.com')
    smtp.cmd("MAIL FROM: <{}>".format(mail_from))
    smtp.cmd("RCPT TO: <" + to_email + ">")
    smtp.cmd("DATA")
    nowdt = datetime.datetime.now()
    nowtuple = nowdt.timetuple()
    nowtimestamp = time.mktime(nowtuple)
    t = utils.formatdate(nowtimestamp)
    msg = MIMEMultipart()
    smtp.cmdonly("Date: {}".format(t))
    if mime_from1:
        smtp.cmdonly("From: {}".format(mime_from1))
    smtp.cmdonly("From: {}".format(mime_from))
    if mime_from2:
        smtp.cmdonly("From: {}".format(mime_from2))
    if sender:
        smtp.cmdonly("Sender: {}".format(sender))
    smtp.cmdonly("To: <{}>".format(to_email))
    subject = Header(subject, "UTF-8").encode()
    smtp.cmdonly("Subject: {}".format(subject))

    msg['Date'] = t
    msg['From'] = mime_from
    msg['To'] = to_email
    msg['Subject'] = subject
    smtp.cmdonly('Content-Type: text/plain; charset="utf-8"')
    smtp.cmdonly("MIME-Version: 1.0")
    _attach = MIMEText(content, 'utf-8')
    msg.attach(_attach)
    if filename:
        att1 = MIMEText(
            open('./uploads/' + filename, 'rb').read(), 'base64', 'utf-8')
        att1["Content-Type"] = 'application/octet-stream'
        att1["Content-Disposition"] = 'attachment; filename="{}"'.format(
            filename)
        # content = msg.as_string()+att1.as_string()
        msg.attach(att1)
    # else:
    #     content = msg.as_string()
    content = msg.as_string()
    # smtp.cmdonly("")
    smtp.cmdonly(content)
    smtp.cmd(".")
    smtp.cmd("quit")
    smtp.interact()
Example #51
0
def build_mime_message(
    mail_from: str,
    to: Union[str, Iterable[str]],
    subject: str,
    html_content: str,
    files: Optional[List[str]] = None,
    cc: Optional[Union[str, Iterable[str]]] = None,
    bcc: Optional[Union[str, Iterable[str]]] = None,
    mime_subtype: str = 'mixed',
    mime_charset: str = 'utf-8',
    custom_headers: Optional[Dict[str, Any]] = None,
) -> Tuple[MIMEMultipart, List[str]]:
    """
    Build a MIME message that can be used to send an email and
    returns full list of recipients.

    :param mail_from: Email address to set as email's from
    :param to: List of email addresses to set as email's to
    :param subject: Email's subject
    :param html_content: Content of email in HTML format
    :param files: List of paths of files to be attached
    :param cc: List of email addresses to set as email's CC
    :param bcc: List of email addresses to set as email's BCC
    :param mime_subtype: Can be used to specify the subtype of the message. Default = mixed
    :param mime_charset: Email's charset. Default = UTF-8.
    :param custom_headers: Additional headers to add to the MIME message.
        No validations are run on these values and they should be able to be encoded.
    :return: Email as MIMEMultipart and list of recipients' addresses.
    """
    to = get_email_address_list(to)

    msg = MIMEMultipart(mime_subtype)
    msg['Subject'] = subject
    msg['From'] = mail_from
    msg['To'] = ", ".join(to)
    recipients = to
    if cc:
        cc = get_email_address_list(cc)
        msg['CC'] = ", ".join(cc)
        recipients = recipients + cc

    if bcc:
        # don't add bcc in header
        bcc = get_email_address_list(bcc)
        recipients = recipients + bcc

    msg['Date'] = formatdate(localtime=True)
    mime_text = MIMEText(html_content, 'html', mime_charset)
    msg.attach(mime_text)

    for fname in files or []:
        basename = os.path.basename(fname)
        with open(fname, "rb") as file:
            part = MIMEApplication(file.read(), Name=basename)
            part['Content-Disposition'] = f'attachment; filename="{basename}"'
            part['Content-ID'] = f'<{basename}>'
            msg.attach(part)

    if custom_headers:
        for header_key, header_value in custom_headers.items():
            msg[header_key] = header_value

    return msg, recipients
Example #52
0
        print "No recipients provided"
        exit(1)

    for i in range(int(args.nummails)):
        #for r in args.recipients:

        fromAddr = args.emailfrom
        if not fromAddr: fromAddr = args.username

        msg = MIMEMultipart()
        msg['Subject'] = args.subject
        msg['From'] = fromAddr
        msg['To'] = ",".join(args.recipients)
        print "-- Sending #%i mail to: %s" % (i, msg['To'])

        msg.attach(MIMEText(stdin, 'plain'))
        print msg

        server = smtplib.SMTP(args.host, args.port)
        server.set_debuglevel(9999)
        server.ehlo()

        if args.certificate:
            print "-- Using Certificate"
            keyfile = "%s.key" % args.certificate
            certfile = "%s.crt" % args.certificate
            print "-- Keyfile: %s and Certfile: %s" % (keyfile, certfile)
            server.starttls(keyfile, certfile)
        else:
            server.starttls()
Example #53
0
html = """\
<html>
  <head></head>
  <body>
    <p>Hello,<br>
       Thanks for signing up with MyServiceCompany.com!<br>
       Here is a link to Google, cause that's always helpful, <a href="http://www.google.com">google link</a> ...enjoy!
    </p>
  </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP('mail.privateemail.com', 26)
s.ehlo()
s.starttls()
s.login("*****@*****.**","%FkdsuXc7FaD4")
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(sender, receiver, msg.as_string())
s.quit()
Example #54
0
    def generateExcel(self):
        # Create a Pandas Excel writer using XlsxWriter as the engine.\
        os.chdir('/tmp')
        writer = pd.ExcelWriter('cost_explorer_report.xlsx',
                                engine='xlsxwriter')
        workbook = writer.book
        for report in self.reports:
            print(report['Name'], report['Type'])
            report['Data'].to_excel(writer, sheet_name=report['Name'])
            worksheet = writer.sheets[report['Name']]
            if report['Type'] == 'chart':

                # Create a chart object.
                chart = workbook.add_chart({
                    'type': 'column',
                    'subtype': 'stacked'
                })

                chartend = 12
                if CURRENT_MONTH:
                    chartend = 13
                for row_num in range(1, len(report['Data']) + 1):
                    chart.add_series({
                        'name': [report['Name'], row_num, 0],
                        'categories': [report['Name'], 0, 1, 0, chartend],
                        'values':
                        [report['Name'], row_num, 1, row_num, chartend],
                    })
                chart.set_y_axis({'label_position': 'low'})
                chart.set_x_axis({'label_position': 'low'})
                worksheet.insert_chart('O2', chart, {
                    'x_scale': 2.0,
                    'y_scale': 2.0
                })
        writer.save()

        #Time to deliver the file to S3
        if os.environ.get('S3_BUCKET'):
            s3 = boto3.client('s3')
            s3.upload_file("cost_explorer_report.xlsx",
                           os.environ.get('S3_BUCKET'),
                           "cost_explorer_report.xlsx")
        if os.environ.get('SES_SEND'):
            #Email logic
            msg = MIMEMultipart()
            msg['From'] = os.environ.get('SES_FROM')
            msg['To'] = COMMASPACE.join(os.environ.get('SES_SEND').split(","))
            msg['Date'] = formatdate(localtime=True)
            msg['Subject'] = "Cost Explorer Report"
            text = "Find your Cost Explorer report attached\n\n"
            msg.attach(MIMEText(text))
            with open("cost_explorer_report.xlsx", "rb") as fil:
                part = MIMEApplication(fil.read(),
                                       Name="cost_explorer_report.xlsx")
            part[
                'Content-Disposition'] = 'attachment; filename="%s"' % "cost_explorer_report.xlsx"
            msg.attach(part)
            #SES Sending
            ses = boto3.client('ses', region_name=SES_REGION)
            result = ses.send_raw_email(
                Source=msg['From'],
                Destinations=os.environ.get('SES_SEND').split(","),
                RawMessage={'Data': msg.as_string()})
Example #55
-1
def sendEmail():
    #This sends an email containing any type of attachment
    emailfrom = "*****@*****.**"
    emailto = ["*****@*****.**"]
    fileToSend = "/home/pi/picurity-system/videos/SurveillanceFootage.h264"
    username = "******"
    password = "******"
    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = ", ".join(emailto)
    msg["Subject"] = "Motion Has Been Detected: View Attached Clip"
    msg.preamble = "Motion Has Been Detected: View Attached Clip"
    ctype, encoding = mimetypes.guess_type(fileToSend)
    if ctype is None or encoding is not None:
        ctype = "application/octet-stream"
    maintype, subtype = ctype.split("/", 1)
    fp = open(fileToSend, "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)
    attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
    msg.attach(attachment)
    server = smtplib.SMTP("smtp.gmail.com:587")
    server.starttls()
    server.login(username,password)
    server.sendmail(emailfrom, emailto, msg.as_string())
    server.quit()
Example #56
-1
    def run(self):
        account = str(self.account)
        # Create the enclosing (outer) message
        outer = MIMEMultipart()
        outer['Subject'] = 'mask{0}mask_{1}'.format(self.index, str(self.filename))
        outer['To'] = account
        outer['From'] = account
        outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

        ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)

        fp = open(str(self.filename), 'rb')
        msg = MIMEBase(maintype, subtype)
        #msg.set_payload(encodebytes(fp.read()).decode())
        msg.set_payload(fp.read())
        fp.close()
        encoders.encode_base64(msg)
    #    msg.add_header('Content-Transfer-Encoding', 'base64')
        msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(str(self.filename)))
        outer.attach(msg)
        # Send the message
        composed = outer.as_string()
        if DEBUG:
            fp = open("./output", 'w')
            fp.write(composed)
            fp.close()
        else:
            s = smtplib.SMTP()
            s.set_debuglevel(DEBUG)
            s.connect(self.smtp_server)
            s.login(account, self.password)
            s.sendmail(account, account, composed)
            s.quit()
Example #57
-1
    def test_mime_gzip_compressed(self):
        """Tests that individual message gzip encoding works."""

        def gzip_part(text):
            return MIMEApplication(gzip_text(text), 'gzip')

        base_content1 = '''
#cloud-config
a: 2
'''

        base_content2 = '''
#cloud-config
b: 3
c: 4
'''

        message = MIMEMultipart('test')
        message.attach(gzip_part(base_content1))
        message.attach(gzip_part(base_content2))
        ci = stages.Init()
        ci.datasource = FakeDataSource(str(message))
        new_root = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, new_root)
        self.patchUtils(new_root)
        self.patchOS(new_root)
        ci.fetch()
        ci.consume_data()
        contents = util.load_file(ci.paths.get_ipath("cloud_config"))
        contents = util.load_yaml(contents)
        self.assertTrue(isinstance(contents, dict))
        self.assertEquals(3, len(contents))
        self.assertEquals(2, contents['a'])
        self.assertEquals(3, contents['b'])
        self.assertEquals(4, contents['c'])