Ejemplo n.º 1
1
def send_mail(message):
    try:
        smtpObj = SMTP_SSL(mail_host,465)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print "邮件发送成功"
    except smtplib.SMTPException:
        print "无法发送邮件"
Ejemplo n.º 2
0
def sendmail(to_addrs, subject, text):

    server = config.get('smtp_server')
    use_tls = asbool(config.get('smtp_use_tls'))
    username = config.get('smtp_username')
    password = config.get('smtp_password')
    from_addr = config.get('admin_email_from')

    log.debug('Sending mail via %s' % server)

    if use_tls:
        s = SMTP_SSL()
    else:
        s = SMTP()
    s.connect(server)
    if username:
        s.login(username, password)
    msg = MIMEText(text, _charset='utf-8')
    msg['From'] = from_addr
    msg['Reply-To'] = from_addr
    if isinstance(to_addrs, basestring):
        msg['To'] = to_addrs
    else:
        msg['To'] = ', '.join(to_addrs)
    msg['Subject'] = subject
    s.sendmail(from_addr, to_addrs, msg.as_string())
    s.quit()
Ejemplo n.º 3
0
    def _sendMail(self, message, request):
	
        if message['subject']=='QUESTION':
            txt='\r\n'+'NAME: '+message['name']+'\r\n'+'\r\n'+'EMAIL: '+message['email']+'\r\n'+'\r\n'+'QUESTION: '+message['question']+'\r\n'
        elif message['subject']=='ORDER':
            txt='\r\n'+'NAME: '+message['name']+'\r\n'+'\r\n'+'EMAIL: '+message['email']+'\r\n'+'\r\n'+ \
			     'ENTIRE LANGUAGE: '+message['entire_language']+'\r\n'+'CAPTION LANGUAGE: '+message['caption_language']+ \
				 '\r\n'+'VIDEO DURATION: '+message['duration']+'\r\n'+'TIME LIMIT: '+message['time_limit']+ \
				 '\r\n'+'VOICE OVER: '+message['voice_over']+'\r\n'+'DISCOUNT: '+message['discount']+'\r\n'+ \
				 'VIDEO LINK:'+message['videolink']+'\r\n'+'SPECIAL: '+message['special']	
        elif message['subject']=='CUSTOM ORDER':
            txt='\r\n'+'NAME: '+message['name']+'\r\n'+'\r\n'+'EMAIL: '+message['email']+'\r\n'+'\r\n'+'COMPANY: '+ \
			     message['company']+'\r\n'+'REQUIREMENTS: '+message['requirements']
        elif message['subject']=='FREE MINUTE':
            txt='\r\n'+'EMAIL: '+message['email']+'\r\n'
			
        msg=MIMEText(txt)
        msg['Subject']=message['subject']
        msg['From']=message['email']
        msg['To']=self.addr		
        smtp = SMTP_SSL(self.hst)
        smtp.login(self.addr,self.psswd)
        smtp.sendmail(self.addr,self.addr,msg.as_string())
        request.write('Your mail sent.')
        request.finish()
Ejemplo n.º 4
0
    def render_POST(self, request):
        message = ast.literal_eval(request.content.read())
        if message['subject']=='QUESTION':
            txt='\r\n'+'NAME: '+message['name']+'\r\n'+'\r\n'+'EMAIL: '+message['email']+'\r\n'+'\r\n'+'QUESTION: '+message['question']+'\r\n'  
        elif message['subject']=='ORDER':
            txt='\r\n'+'NAME: '+message['name']+'\r\n'+'\r\n'+'EMAIL: '+message['email']+'\r\n'+'\r\n'+ \
			     'ENTIRE LANGUAGE: '+message['entire_language']+'\r\n'+'CAPTION LANGUAGE: '+message['caption_language']+ \
				 '\r\n'+'VIDEO DURATION: '+message['duration']+'\r\n'+'TIME LIMIT: '+message['time_limit']+ \
				 '\r\n'+'VOICE OVER: '+message['voice_over']+'\r\n'+'DISCOUNT: '+message['discount']+'\r\n'+ \
				 'VIDEO LINK:'+message['videolink']+'\r\n'+'SPECIAL: '+message['special']
        elif message['subject']=='CUSTOM ORDER':
            txt='\r\n'+'NAME: '+message['name']+'\r\n'+'\r\n'+'EMAIL: '+message['email']+'\r\n'+'\r\n'+'COMPANY: '+ \
			     message['company']+'\r\n'+'REQUIREMENTS: '+message['requirements']
        elif message['subject']=='FREE MINUTE':
            txt='\r\n'+'EMAIL: '+message['email']+'\r\n'
		
        msg=MIMEText(txt)
        msg['Subject']=message['subject']
        msg['From']=message['email']
        msg['To']=self.addr		
        
        request.setHeader("Access-Control-Allow-Origin", "*")
        smtp = SMTP_SSL(self.hst)
        smtp.login(self.addr,self.psswd)
        smtp.sendmail(self.addr,self.addr,msg.as_string())
        return 'Your mail sent.' 
Ejemplo n.º 5
0
 def __init__(self, **kw):
     args = {}
     for k in ('host', 'port', 'local_hostname', 'keyfile', 'certfile', 'timeout'):
         if k in kw:
             args[k] = kw[k]
     SMTP_SSL.__init__(self, **args)
     SMTPClientWithResponse.__init__(self, **kw)
Ejemplo n.º 6
0
def send(message):
    global datas
    global numbers
    s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
    s.login(datas[0],datas[1])
    for n in numbers:
        s.sendmail(datas[0], numbers[n], str(message))
    s.quit
Ejemplo n.º 7
0
 def _open(self):
     if self.conn:
         return
     conn = SMTP_SSL(self.config_d['smtp_host'],
                     self.config_d['smtp_port'])
     conn.ehlo()
     conn.login(self.config_d['smtp_user'],
                self.config_d['smtp_password'])
     self.conn = conn
Ejemplo n.º 8
0
 def render_POST(self, request):
     print request.content.read()
     addr='*****@*****.**'
     msg=MIMEMultipart()
     msg['From']=msg['To']=addr
     request.setHeader("Access-Control-Allow-Origin", "*")
     smtp = SMTP_SSL('smtp.yandex.ru:465')
     smtp.login('*****@*****.**','48919o6')
     smtp.sendmail(addr,addr,msg.as_string())
     return 'Your mail sent.' 
Ejemplo n.º 9
0
def landing_customer_contacts(customer_email, customer_phone, customer_session):
    """
    Функция отправки контактных данных полученных с лендинга.

    :return:
    """

    msg = email.MIMEMultipart.MIMEMultipart()
    from_addr = "*****@*****.**"
    to_addr = "[email protected], [email protected]"

    msg['From'] = from_addr
    msg['To'] = to_addr
    text = "\tE-mail: %s \n\tТелефон: %s \n" % (customer_email, customer_phone)
    text += "\tДата и время: %s \n" % datetime.datetime.now()
    text += "Параметры сессии: \n "
    for a,b in customer_session.items():
        text += "\t%s : %s \n" % (a, b)

    msg['Subject'] = Header("Контакты с лендинга Conversation parser", "utf8")
    body = "Оставлены контакты. \n" + text
    msg.preamble = "This is a multi-part message in MIME format."
    msg.epilogue = "End of message"

    msg.attach(email.MIMEText.MIMEText(body, "plain", "UTF-8"))

    smtp = SMTP_SSL()
    smtp.connect(smtp_server)
    smtp.login(from_addr, "Cthutq123")
    text = msg.as_string()
    smtp.sendmail(from_addr, to_addr.split(","), text)
    smtp.quit()
Ejemplo n.º 10
0
def SendingEmail(email,password,message,date):
    SMTPserver = 'smtp.gmail.com'
    sender = email
    receivers = ['*****@*****.**','*****@*****.**']    
    
    # typical values for text_subtype are plain, html, xml
    text_subtype = 'plain'
        
    content = message
    
    subject="Bluetooth Data Daily Report: %s" % (date)
    
    USERNAME = email
    PASSWORD = password
    
    try:
        msg = MIMEText(content, text_subtype)
        msg['Subject']= subject
        msg['From'] = sender # some SMTP servers will do this automatically, not all
    
        conn = SMTP(SMTPserver)
        conn.set_debuglevel(False)
        conn.login(USERNAME, PASSWORD)
        try:
            conn.sendmail(sender, receivers, msg.as_string())
        finally:
            conn.close()
    
    except Exception, exc:
        sys.exit( "mail failed; %s" % str(exc) ) # give a error message
Ejemplo n.º 11
0
    def run(self):

        if self.getSender() and \
           self.getRecipient() and \
           self.getSubject() and \
           self.getContent():

            try:
                message = MIMEText(self.getContent(), self.getTextSubtype())
                message['Subject'] = self.getSubject()
                message['From'] = self.getSender()

                connection = SMTP(self.getSmtpServer(), self.getPort())
                connection.set_debuglevel(False)
                connection.login(self.getUsername(), self.getPasswd())

                try:
                    connection.sendmail(self.getSender(),
                                        self.getRecipient(),
                                        message.as_string())
                finally:
                    connection.close()
            except Exception, e:
                print "Message to {0} failed: {1}".format(
                                                self.getRecipient(), e)
Ejemplo n.º 12
0
    def SendMail(self):
        USERNAME = "******"
        PASSWORD = "******"
        SMTPserver = 'smtp.YOURMAIL.com'

        for permalink in self.commentswithtext:
            body = self.commentswithtext[permalink]
            if body[:len(self.breakstring)] != self.breakstring:
                content = "FYI - " + permalink + """
                """ + self.commentswithtext[permalink] + """

                Thanks!
                """
                content = content.encode('utf-8')
                text_subtype = 'plain'
                msg = MIMEText(content,'plain','utf-8')
                msg['Subject']=  "New Reddit Comment"
                msg['From']   = "*****@*****.**" 

                conn = SMTP(SMTPserver)
                conn.set_debuglevel(False)
                conn.login(USERNAME, PASSWORD)
                try:
                    print("Sending Mail -- " + permalink)
                    conn.sendmail(msg['From'],msg['From'], msg.as_string())
                finally:
                    conn.close()     

                # Mark that we've now sent this message      
                self.commentswithtext[permalink] = self.breakstring + str(   int(time.time())   )
Ejemplo n.º 13
0
def mail(directory):
    subject="[ CS 260 ][ Grade ][ REVIEW ] - Homework 3 Written"
    i = 0
    for root, dirs, filenames in os.walk(directory):
        for f in filenames:
                content= open(os.path.join(root,f) ).read()
                destination = []
                rex = re.compile("(.*)hw3")
                destination.append(rex.search(f).groups()[0] + "@drexel.edu")
                print "Mailing to Destination " , rex.search(f).groups()[0]
                try:
                    msg = MIMEText(content, text_subtype)
                    msg['Subject']= subject
                    msg['From'] = "TA Nagesh<*****@*****.**>" # some SMTP servers will do this automatically, not all

                    conn = SMTP(SMTPserver)
                    conn.set_debuglevel(False)
                    conn.login(USERNAME, PASSWORD)
                    try:
                        conn.sendmail(sender, destination, msg.as_string())
                    finally:
                        conn.close()

                except Exception, exc:
                    sys.exit( "mail failed; %s" % str(exc) ) # give a error message
Ejemplo n.º 14
0
def send_email(content):
    if content == "":
        return False

    destination = [DESTINATION]

    # typical values for text_subtype are plain, html, xml
    text_subtype = 'plain'

    from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
    from email.mime.text import MIMEText

    try:
        msg = MIMEText(content, text_subtype, "utf-8")
        msg['Subject'] = SUBJECT_EMAIL
        msg['From'] = YA_USER
        msg['To'] = DESTINATION
        conn = SMTP(SMTP_SERVER)
        conn.set_debuglevel(False)
        conn.login(YA_USER, YA_PASS)

        stat = False

        try:
            conn.sendmail(YA_USER, destination, msg.as_string())
            stat = True
        finally:
            conn.close()
    except Exception, exc:
        pass
Ejemplo n.º 15
0
def contact_form(request):

    f = ContactForm(request.POST)   # empty form initializes if not a POST request

    if 'POST' == request.method and 'form.submitted' in request.params:
        if f.validate():
            #TODO: Do email sending here.
            to = '[email protected],[email protected]'
            user_from = request.POST['email']
            me = ('*****@*****.**')
            subject = request.POST['subject']
            msg = str (request.POST['message']+"\n\nFrom : "+user_from)
            msg = 'Subject: %s' % (subject) + ' \n\n%s' % (msg)
            password= '******'
            # send it via gmail
            s = SMTP_SSL('smtp.gmail.com', 465)
            #s = smtplib.SMTP('smtp.live.com', 25) #4 hotmail
            s.set_debuglevel(0)
            #s = smtplib.SMTP('localhost')
            try:
                s.login(me, password)
                s.sendmail(me, to.split(","), msg)
            finally:
                s.quit()

            request.session.flash("Your message has been sent!")
            return HTTPFound(location=request.route_url('home'))

    return {'contact_form': f}
Ejemplo n.º 16
0
def sendEmail(text, email_class, identity_dict, email_dict, state, solved_pq = False):
	retries, count = 3, 0
	while count < retries:
		try:
			message = composeMessage(text, email_class, identity_dict, email_dict, state, solved_pq)
			own_addr = identity_dict['Email']
			own_name = ' '.join([identity_dict['First_name'], identity_dict['Last_name']])
			destination_addr = email_dict['Reply-To']
			text_subtype = 'plain'
			mime_msg = MIMEText(message, text_subtype)
			mime_msg['Subject'] = composeSubject(email_dict)
			mime_msg['From'] = own_name + '<' + own_addr + '>'
			if destination_addr in getIdentityEmails():
				break
			mime_msg['To'] = destination_addr
			server_addr = identity_dict['SMTP']
			conn = SMTP_SSL(server_addr)
			conn.set_debuglevel(False)
			conn.login(identity_dict['Username'], identity_dict['Password'])
			try:
				conn.sendmail(own_addr, destination_addr, mime_msg.as_string())
			finally:
				print "Send email!"
				conn.close()
				syncGuardian(mime_msg, identity_dict)
		except Exception:
			count += 1
			continue
		pq_status, pq_result = hasPQ(text), None
		if pq_status:
			pq_result = hasPQ(text).values()[0]
		return {'Date': time.ctime(), 'Sender': own_addr, 'Receiver': destination_addr, 'Subject': composeSubject(email_dict), 'Body': message, 'First_name': identity_dict['First_name'], 'Last_name': identity_dict['Last_name'], 'Origin': 'SYSTEM', 'PQ': pq_result}
	return None
Ejemplo n.º 17
0
def send_mail(receivers, subject, content, attachment=None, filename=None):
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = config.FROM_EMAIL
    msg['To'] = receivers

    if config.DEV_ENV:
        msg['To'] = config.TEST_TO_EMAIL

    msg.preamble = 'Multipart message.\n'

    part = MIMEText(content)
    msg.attach(part)

    if attachment:
        part = MIMEApplication(open(attachment, "rb").read())
        part.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(part)

    mailer = SMTP_SSL(config.SMTP_SERVER, config.SMTP_PORT)
    # mailer.ehlo()
    # mailer.starttls()
    mailer.login(config.USERNAME, config.PASSWORD)
    mailer.set_debuglevel(1)
    mailer.sendmail(msg['From'], msg['To'].split(', '), msg.as_string())
    mailer.close()
Ejemplo n.º 18
0
def sendmail(to, app, attach0=False, attach1=False):

    from smtplib import SMTP_SSL as SMTP
    from email.MIMEText import MIMEText

    destination = [to]

    # read attach
    contentattach = ''
    if attach0 and not os.stat("%s" % attach0).st_size == 0: 
        fp = open(attach0,'rb')
        contentattach += '------------------ Error begin\n\n'
        contentattach += fp.read()
        contentattach += '\n------------------ Error end'
        fp.close()

    if attach1 and not os.stat("%s" % attach1).st_size == 0: 
        fp = open(attach1,'rb')
        contentattach += '\n\n------------------ Success begin\n\n'
        contentattach += fp.read()
        contentattach += '\n------------------ Success end'
        fp.close()

    msg = MIMEText(contentattach, 'plain')
    msg['Subject'] = "Mr.Script %s" % app
    msg['From'] = sender
                    
    try:
        conn = SMTP(smtpserver)
        conn.set_debuglevel(False)
        conn.login(username, password)
        conn.sendmail(sender, destination, msg.as_string())
        conn.close()
    except:
        print '    *** Error trying send a mail. Check settings.'
def sendEmail( destination, subject, content ):

    # don't try this if we are offline
    if not internet_on(): return
    
    SMTPserver = 'smtp.gmail.com'
    sender =     '*****@*****.**'

    USERNAME = "******"
    PASSWORD = "******"

    # typical values for text_subtype are plain, html, xml
    text_subtype = 'plain'

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

    try:
        msg = MIMEText(content, text_subtype)
        msg['Subject']= subject
        msg['From']   = sender # some SMTP servers will do this automatically, not all

        conn = SMTP(SMTPserver)
        conn.set_debuglevel(False)
        conn.login(USERNAME, PASSWORD)
        try:
            conn.sendmail(sender, destination, msg.as_string())
        finally:
            conn.close()

    except Exception as e:
        errmsg = str(traceback.format_exception( *sys.exc_info() ));
        Logger.info( "error when trying to send email: " + errmsg );
        sys.exit( "mail failed; %s" + errmsg ) # give a error message
Ejemplo n.º 20
0
def create_validator(email):
	key = list(string.ascii_uppercase + string.ascii_lowercase + string.digits)
	random.shuffle(key)
	key = ''.join(key[:25])
	item = ValidationQueue(key=key, email=email)
	item.save()

	text = '''
	Hello,
		Please go to http://127.0.0.1:8000/b/confirm_account/''' + key + '''/ to validate your account.

		Validation will take up to a minute. Please do not interrupt the process by closing the tab.
	'''
	message = MIMEText(text, 'plain')
	message['Subject'] = 'Verify Account'
	to_address = email
	try:
		conn = SMTP('smtp.gmail.com')
		conn.set_debuglevel(True)
		conn.login(from_address, password)
		try:
			conn.sendmail(from_address, to_address, message.as_string())
		finally:
			conn.close()
	except Exception:
		print("Failed to send email")
Ejemplo n.º 21
0
def sendMail(RECIPIENT,SUBJECT,TEXT):
    import sys
    import os
    import re
    from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
    # from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)
    from email.MIMEText import MIMEText
    SMTPserver = 'smtp.gmail.com'
    sender =     '*****@*****.**'
    destination = [RECIPIENT]

    USERNAME = "******"
    PASSWORD = "******"

    # typical values for text_subtype are plain, html, xml
    text_subtype = 'plain'

    
    try:
        msg = MIMEText(TEXT, text_subtype)
        msg['Subject']=       SUBJECT
        msg['From']   = sender # some SMTP servers will do this automatically, not all

        conn = SMTP(SMTPserver)
        conn.set_debuglevel(False)
        conn.login(USERNAME, PASSWORD)
        try:
            conn.sendmail(sender, destination, msg.as_string())
        finally:
            conn.close()
    
    except Exception, exc:
        sys.exit( "mail failed; %s" % str(exc) ) # give a error message
Ejemplo n.º 22
0
def sendmail(to_mails, message):
    # Update settings
    apply_db_settings(flask_app.flask_app)

    mail = 'From: {}\nTo: {}\nSubject: {}\n\n{}'.format(
        flask_app.flask_app.config.get('EMAIL_EMAIL_FROM'),
        to_mails,
        flask_app.flask_app.config.get('EMAIL_SUBJECT'),
        message
    ).encode(encoding='utf-8')

    server_str = '{}:{}'.format(flask_app.flask_app.config.get('EMAIL_HOST', '127.0.0.1'),
                                flask_app.flask_app.config.get('EMAIL_PORT', 25))
    server = SMTP_SSL(server_str) if flask_app.flask_app.config.get('EMAIL_ENCRYPTION', 0) == 2 \
        else SMTP(server_str)

    if flask_app.flask_app.config.get('EMAIL_ENCRYPTION', 0) == 1:
        server.starttls()

    if flask_app.flask_app.config.get('EMAIL_AUTH', 0):
        server.login(flask_app.flask_app.config.get('EMAIL_LOGIN'),
                     flask_app.flask_app.config.get('EMAIL_PASSWORD'))
    server.sendmail(flask_app.flask_app.config.get('EMAIL_EMAIL_FROM'),
                    to_mails,
                    mail)
    server.quit()
Ejemplo n.º 23
0
def send_reminder_email(content, to, subject):


    to = ['*****@*****.**', '*****@*****.**']
    text_subtype = 'plain'

    try:
        msg = MIMEText(content.encode('utf-8'), text_subtype)
        msg.set_charset('utf-8')

        msg['Subject']  = subject
        msg['From']     = smtp_conf['from']
        msg['To']       = ','.join(to)
        msg['Reply-To'] = smtp_conf['reply-to']

        conn = SMTP(smtp_conf['server'], 465)
        conn.set_debuglevel(False)
        conn.login(smtp_conf['user'], smtp_conf['pass'])
        try:
            conn.sendmail(smtp_conf['from'], to, msg.as_string())
        finally:
            conn.close()

    except Exception, exc:
        sys.exit( "mail failed; %s" % str(exc) ) # give a error message
Ejemplo n.º 24
0
def sendMail(emailTo, subject, msgText, fileAddr):
	filepath = fileAddr
	basename = os.path.basename(filepath)
	address = "*****@*****.**"

	# Compose attachment
	part = MIMEBase('application', "octet-stream")
	part.set_payload(open(filepath,"rb").read() )
	Encoders.encode_base64(part)
	part.add_header('Content-Disposition', 'attachment; filename="%s"' % basename)
	part3 = MIMEBase('application', "octet-stream")
	part3.set_payload(open(os.getcwd() + '/plan_rabot_po_saitu_na_god.xlsx',"rb").read() )
	Encoders.encode_base64(part3)
	part3.add_header('Content-Disposition', 'attachment; filename="plan_rabot_po_saitu_na_god.xlsx"')
	part2 = MIMEText(msgText, 'plain')

	# Compose message
	msg = MIMEMultipart()
	msg['From'] = 'Михаил Юрьевич Бубновский <*****@*****.**>'
	msg['To'] = emailTo
	msg['Subject'] = subject

	msg.attach(part2)
	msg.attach(part)
	msg.attach(part3)

	# Send mail
	smtp = SMTP_SSL()
	smtp.connect('smtp.yandex.ru')
	smtp.login(address, 'biksileev')
	smtp.sendmail(address, emailTo, msg.as_string())
	smtp.quit()
Ejemplo n.º 25
0
  def mail_send(self, subject, emailaddr, key, msg):
    if self._limit:
      self._clean_array()
      epoch = time.time()
      if not key in self._array:
        self._array[key] = epoch
      else:
        ts = self._array.get(key)
        if epoch - ts < self._timeout:
          return self.RET_NOTAUTH
        else:
          self._array[key] = epoch

    if self.DEBUG:
      self._debug('new mail:')
      self._debug('subject: %s' % (subject))
      self._debug('addr: %s' % (emailaddr))
      self._debug('key: %s' % (key))
      self._debug('msg: %s' % (msg))

    try:
      mailserver = SMTP(self._addr)
      mailserver.set_debuglevel(self._mail_debug)
      mailserver.login(self._username, self._password)
      date = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')
      msg = self.MAIL_MSG % (self._srcmail, emailaddr, subject, date, msg)
      mailserver.sendmail(self._srcmail, emailaddr, msg)
      mailserver.quit()
    except Exception as msg:
      self._error(str(msg))
      return self.RET_ERR
    return self.RET_SUCCESS
Ejemplo n.º 26
0
def send_token(token, address, server, username, password):

    content =  "Dein Token fuer den Zugang zum OpenLab ist da:\n\n"
    content += "\t" + token + "\n\n"
    content += "Nutze diese Links:\n"
    content += "- Tuer oeffnen: https://labctl.ffa/sphincter/?action=open&token=" + token + "\n"
    content += "- Tuer schliessen: https://labctl.ffa/sphincter/?action=close&token=" + token + "\n"
    content += "- Status abfragen: https://labctl.ffa/sphincter/?action=state"

    sender = '*****@*****.**'

    try:
        msg = MIMEText(content, 'plain')
        msg['Subject'] = 'Dein OpenLab-Zugang'
	msg['Date'] = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
        msg['From']    = sender

        conn = SMTP(server)
        conn.set_debuglevel(False)
        conn.login(username, password)
        try:
            conn.sendmail(sender, [address], msg.as_string())
        finally:
            conn.close()

    except Exception, exc:
        sys.exit( "mail failed; %s" % str(exc) )
Ejemplo n.º 27
0
def sent(filepath):
    from smtplib import SMTP_SSL
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email import Encoders
    import os
    
    #filepath = "/path/to/file"
    basename = os.path.basename(filepath)
    address = 'adr'
    address_to = "*****@*****.**"
    
    # Compose attachment
    part = MIMEBase('application', "octet-stream")
    part.set_payload(open(filepath,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % basename)
    
    # Compose message
    msg = MIMEMultipart()
    msg['From'] = address
    msg['To'] = address_to
    msg.attach(part)
    
    # Send mail
    smtp = SMTP_SSL()
    smtp.connect('smtp.yandex.ru')
    smtp.login(address, 'password')
    smtp.sendmail(address, address_to, msg.as_string())
    smtp.quit()
Ejemplo n.º 28
0
    def sendMessage(self, sender, password, recipient, subject, body, attachmentFilenames=[]):
        if type(attachmentFilenames) != list:
            attachmentFilenames = [attachmentFilenames]

        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = recipient
        msg['Date'] = formatdate(localtime=True)

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

        for filename in attachmentFilenames:
            part = MIMEBase('application', "octet-stream")
            part.set_payload(open(filename, "rb").read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % basename(filename))
            msg.attach(part)

        self.out.put("connecting...")
        mailServer = SMTP_SSL(self.smtpHost, 465)
        mailServer.ehlo()
        self.out.put("logging in...")
        mailServer.login(sender, password)
        self.out.put("sending...")
        mailServer.sendmail(sender, recipient, msg.as_string())  # raise if email is not sent
        mailServer.quit()
        self.out.put("done.")
Ejemplo n.º 29
0
    def _use_smtp(self, subject, body, path):
        # if self.smtp_server is not provided than don't try to send email via smtp service
        logging.debug('SMTP Mail delivery: Started')
        # change to smtp based mail delivery
        # depending on encrypted mail delivery, we need to import the right lib
        if self.smtp_encryption:
            # lib with ssl encryption
            logging.debug('SMTP Mail delivery: Import SSL SMTP Lib')
            from smtplib import SMTP_SSL as SMTP
        else:
            # lib without encryption (SMTP-port 21)
            logging.debug('SMTP Mail delivery: Import standard SMTP Lib (no SSL encryption)')
            from smtplib import SMTP
        conn = False
        try:
            outer = MIMEMultipart()
            outer['Subject'] = subject  # put subject to mail
            outer['From'] = 'Your PicoChess computer <{}>'.format(self.smtp_from)
            outer['To'] = self.email
            outer.attach(MIMEText(body, 'plain'))  # pack the pgn to Email body

            ctype, encoding = mimetypes.guess_type(path)
            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                with open(path) as fpath:
                    msg = MIMEText(fpath.read(), _subtype=subtype)
            elif maintype == 'image':
                with open(path, 'rb') as fpath:
                    msg = MIMEImage(fpath.read(), _subtype=subtype)
            elif maintype == 'audio':
                with open(path, 'rb') as fpath:
                    msg = MIMEAudio(fpath.read(), _subtype=subtype)
            else:
                with open(path, 'rb') as fpath:
                    msg = MIMEBase(maintype, subtype)
                    msg.set_payload(fpath.read())
                encoders.encode_base64(msg)
            msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path))
            outer.attach(msg)

            logging.debug('SMTP Mail delivery: trying to connect to ' + self.smtp_server)
            conn = SMTP(self.smtp_server)  # contact smtp server
            conn.set_debuglevel(False)  # no debug info from smtp lib
            if self.smtp_user is not None and self.smtp_pass is not None:
                logging.debug('SMTP Mail delivery: trying to log to SMTP Server')
                conn.login(self.smtp_user, self.smtp_pass)  # login at smtp server

            logging.debug('SMTP Mail delivery: trying to send email')
            conn.sendmail(self.smtp_from, self.email, outer.as_string())
            # @todo should check the result from sendmail
            logging.debug('SMTP Mail delivery: successfuly delivered message to SMTP server')
        except Exception as smtp_exc:
            logging.error('SMTP Mail delivery: Failed')
            logging.error('SMTP Mail delivery: ' + str(smtp_exc))
        finally:
            if conn:
                conn.close()
            logging.debug('SMTP Mail delivery: Ended')
Ejemplo n.º 30
0
    def send(self, *args, **kwargs):
        picture = kwargs.get('pic')

        msg = MIMEMultipart()
        msg['Charset'] = "UTF-8"
        msg['Date'] = formatdate(localtime=True)
        msg['From'] = self.login + '@' + '.'.join(self.smtp.split('.')[1:])
        msg['Subject'] = "Détection d'un mouvement suspect"
        msg['To'] = self.send_to

        msg.attach(MIMEText('', 'html'))

        part = MIMEBase('application', 'octet-stream')
        fp = open(picture, 'rb')
        part.set_payload(fp.read())
        encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', filename=picture)
        msg.attach(part)

        try:
            server = SMTP_SSL(self.smtp, self.port)

            server.set_debuglevel(False)
            server.ehlo
            server.login(self.login, self.password)
            try:
                server.sendmail(self.From, self.send_to, msg.as_string())
            finally:
                server.quit()

        except Exception as e:
            logging.critical("Unable to send an email\n{0}".format(str(e)))
            sys.exit(2)
Ejemplo n.º 31
0
def main() -> None:
    # Load up environment configuration
    load_dotenv(join(dirname(__file__), 'data', '.env'))
    config = Config()

    # Connect to the database
    db = Database(config)

    # Add the connection to the two models.
    holiday = Holiday(db)
    punch = Punch(db)

    # Set the options to have chrome be headless
    op = Options()
    op.add_argument('--headless')

    # Instantiate the driver
    driver = Chrome(options=op)
    driver.implicitly_wait(config.get_implicit_wait())

    # Instantiate the pager
    smtp = SMTP_SSL(GMAIL_DOMAIN)
    pager = PagerDuty(config, smtp)

    # Set the args in a dictionary for future use
    args = {
        'config': config,
        'driver': driver,
        'holiday': holiday,
        'pager': pager,
        'punch': punch
    }

    punch_card_manager = PunchCardManager(args)

    try:
        # Start the process manager
        punch_card_manager.start()
    except:
        exception_type, value = exc_info()[:2]
        pager.alert(
            'PROGRAM CRASH, needs restart.\nException - %s\nValue - %s' %
            (exception_type, value))
Ejemplo n.º 32
0
def send_message():

    host_server = "服务器"
    password="******"
    from_mail = "发件人邮箱地址"
    to_mail = "收件人邮箱地址"
    # 设置邮件格式
    msg = MIMEMultipart()
    msg['Subject'] = Header('摄像头照片','utf-8')
    msg['From'] = from_mail
    msg['To'] = to_mail
    # 把图片作为附件
    msg.attach(MIMEText('照片','html','utf-8'))
    image = MIMEText(open(fileName, 'rb').read(), 'base64', 'utf-8')
    image["Content-Type"] = 'image/jmeg'
    msg.attach(image)
    # 发送
    smtp = SMTP_SSL(host_server)
    smtp.login(from_mail,password)
    smtp.sendmail(from_mail,to_mail,msg.as_string()) # 发送
    smtp.quit()
Ejemplo n.º 33
0
 def sendMail(self, user, failReason="未知错误"):
     try:
         notifConfig = self.config['scripts']['notification']
         print(notifConfig)
         if notifConfig['enabled']:
             sender = notifConfig['email-address']
             receiver = user['email']
             title = notifConfig['title']
             message = failReason
             pw = notifConfig['passport']
             smtp = SMTP_SSL(notifConfig['host'], notifConfig['port'])
             smtp.login(sender, pw)
             msg = MIMEText(message, "plain", 'utf-8')
             msg["Subject"] = Header(title, 'utf-8')
             msg["From"] = sender
             msg["To"] = receiver
             smtp.sendmail(sender, receiver, msg.as_string())
             smtp.quit()
     except:
         raise ScriptError('EMAIL-SEND-ERR',
                           'failed to send error email notification')
Ejemplo n.º 34
0
def send(
    from_addr: str,
    password: str,
    to_addrs: Sequence[str],
    subject: str,
    content: str,
):
    SMTP_SERVER = config.get('SMTP.SERVER')
    if SMTP_SERVER is None:
        logger().error('SMTP.SERVER is not set')
        return
    with SMTP_SSL(SMTP_SERVER) as server:
        server.login(from_addr, password)
        msg = EmailMessage()
        msg['From'] = from_addr
        msg['To'] = ', '.join(to_addrs)
        msg['Subject'] = subject
        msg.set_content(content)
        server.send_message(msg, from_addr, to_addrs)
Ejemplo n.º 35
0
def send_email(SMTP_host="smtp.163.com",
               nick_name="按时汇报的可乐",  # 邮件昵称
               from_account="*****@*****.**",
               from_passwd="shaowanbo110",
               to_account="*****@*****.**",
               title="Niuco_Service",
               content=""):
    # initial
    email_client = SMTP_SSL(SMTP_host)
    email_client.login(from_account, from_passwd)
    # create msg
    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    HTML = "{}<p>----小纽扣于{}如是向主人汇报</p>".format(content, now)

    msg = MIMEText(HTML, _subtype='html', _charset='utf-8')
    msg['Subject'] = Header(title, 'utf-8')  # subject
    msg['From'] = nick_name
    msg['To'] = to_account
    email_client.sendmail(from_account, to_account, msg.as_string())

    email_client.quit()
Ejemplo n.º 36
0
def send_warming_email(to_addr, subject, text):
    if not to_addr:
        logging.exception('Empty to address. Please check!')
        return
    # 输入Email地址和口令:
    from_addr = EMAIL_CONF['USER']
    code = EMAIL_CONF['CODE']
    # 输入SMTP服务器地址:
    smtp_server = EMAIL_CONF['SMTP']
    msg = MIMEText(text, 'plain', 'utf-8')
    msg['from'] = _format_addr(u'Radar_Dev<%s>' % from_addr)
    msg['to'] = _format_addr(u'<%s>' % to_addr)  # 收件人地址
    msg['Subject'] = Header(subject, 'utf-8').encode()
    try:
        server = SMTP_SSL(smtp_server, port=EMAIL_CONF['SSL_PORT'])
        # server.set_debuglevel(1)
        server.login(from_addr, code)
        server.sendmail(from_addr, [to_addr], msg.as_string())
        server.quit()
    except SMTPException:
        logging.exception('send e-mail to %s failed' % to_addr)
Ejemplo n.º 37
0
    def notify(self, message):
        from smtplib import SMTP, SMTP_SSL
        from email.mime.text import MIMEText

        if message.get_count() <= 0:
            return

        msg = MIMEText(str(message))

        msg['From'] = self._from
        msg['To'] = ', '.join(self._to)
        msg['Subject'] = self._subject
        msg['Date'] = datetime.now().strftime("%m/%d/%Y %H:%M")

        with SMTP_SSL() if self._use_ssl else SMTP() as mailer:
            mailer.connect(self._server, self._port)
            if self._use_auth:
                mailer.login(self._user, self._pass)
            mailer.send_message(msg)
Ejemplo n.º 38
0
 def test_email_connect(self, sender, password):
     success = False
     try:
         smtp_address = "smtp.{}".format(sender.split("@")[1])
         smtp = SMTP_SSL(smtp_address)
         smtp.login(sender, password)
         print('email login successfully')
         success = True
     except Exception as e:
         print('email login fail')
         print(e)
     finally:
         smtp.close()
     return success
Ejemplo n.º 39
0
def send_password_reset_email2(confirmation: str, target_email: str):
    # Create an email content
    msg = MIMEText(f"https://golisten.ucd.ie/find-password?{confirmation}\r\n"
                   f"You are resetting the password and the link will be invalid in 30 minutes\r\n")
    msg['Subject'] = 'Please reset your password'
    msg['From'] = '*****@*****.**'
    msg['To'] = target_email
    # Connect to localhost email server
    conn = SMTP_SSL('localhost')
    try:
        # Login and send email
        conn.sendmail('*****@*****.**', target_email, msg.as_string())
    finally:
        conn.quit()
Ejemplo n.º 40
0
def send_email(newfile, smtpserver, user, password, title, sender, receiver,
               cc):
    f = open(newfile, 'rb')
    mail_body = f.read()
    f.close()
    today = time.strftime('%Y-%m-%d')
    smtpserver = smtpserver
    title = title
    user = user
    password = password
    sender = sender
    receiver = receiver
    cc = cc

    # 发送邮件主题
    subject = title + 'api测试报告%s' % today
    msg = MIMEMultipart('mixed')
    msg_html1 = MIMEText(mail_body, 'html', 'utf-8')  # 邮件内容
    msg.attach(msg_html1)
    msg_html2 = MIMEText(
        '\n' + "<font  size='5' color='red'>注:请点击链接查看详情</font> ", 'html',
        'utf-8')
    msg.attach(msg_html2)
    msg_html = MIMEText(mail_body, 'html', 'utf-8')  # 邮件附件
    msg_html['Content-Disposition'] = 'attachment; filename="TestReport.html"'
    msg.attach(msg_html)
    msg['From'] = sender
    msg['To'] = ';'.join(receiver)
    msg['Cc'] = ';'.join(cc)
    receiver = receiver + cc
    msg['Subject'] = Header(subject, 'utf-8')
    # 连接发送邮件
    try:
        smtp = SMTP_SSL(smtpserver)
        smtp.login(user, password)
        smtp.sendmail(sender, receiver, msg.as_string())
        smtp.quit()
        print("邮件发送成功!")
    except smtplib.SMTPException:
        print("Error:无法发送邮件!")
Ejemplo n.º 41
0
def send_text():
    Path = Pfad()
    with open(Path + "\\data.conf",
              "r") as data:  #liest daten aus .conf file; Positionsabhängig!!!
        Data = data.readlines()
        for i in range(0, 3):
            Data[i] = bdecode(Data[i])
    try:
        message = 'Subject: {}\n\n{}'.format(
            "Your current IP",
            "Your current IP is " + Data[3])  #erstellt message mit Data[2]=IP
        server = SMTP_SSL(
            "smtp.gmail.com", 465
        )  #funktionierrt nur für gmail server. Applikationszugriff uss aktiviert sein
        server.login(Data[0],
                     Data[1])  #Data[0]=your email; Data[1]=your Email password
        server.sendmail(Data[0], Data[2],
                        message)  #Data[0]=your email; Data[2]=receiver email
        server.quit()
        logging("Email was sent")
    except Exception as error:
        logging("Couldn't send email;   " + str(error))
Ejemplo n.º 42
0
def send_photo_to_email():
    # 发送邮件
    host_server = 'smtp.qq.com'
    pwd = '邮箱授权码'  # 打开smtp获取到的授权码
    from_qq_email = '*****@*****.**'  # 发件人
    to_qq_email = '*****@*****.**'  # 收件人
    msg = MIMEMultipart()  # 发送邮件

    msg['Subject'] = Header('摄像头图片', 'UTF-8')  # 邮箱主题
    msg['From'] = from_qq_email
    msg['To'] = to_qq_email
    msg.attach(MIMEText("照片", "html", "UTF-8"))  # 文本内容

    image = MIMEApplication(open('image.jpg', 'rb').read())
    image.add_header('Content-Disposition', 'attachment', filename='image.jpg')
    msg.attach(image)  # 添加附件

    # 执行邮件
    smtp = SMTP_SSL(host_server)
    smtp.login(from_qq_email, pwd)
    smtp.sendmail(from_qq_email, to_qq_email, msg, msg.as_string())
    smtp.quit()
Ejemplo n.º 43
0
def send_mail(mail_title='', mail_content=''):
    from email.mime.text import MIMEText
    from email.header import Header
    from smtplib import SMTP_SSL
    sender = '*****@*****.**'
    receiver = '*****@*****.**'

    with open('web_monitor/config.json', encoding='utf-8') as f:
        config = json.load(f)
        pwd = config['qqmail']  # qq邮箱授权码
        print(pwd)

        smtp = SMTP_SSL('smtp.qq.com')  # ssl登录
        smtp.login(sender, pwd)

        msg = MIMEText(mail_content, "html", 'utf-8')
        msg["Subject"] = Header(mail_title, 'utf-8')
        msg["from"] = sender
        msg["to"] = receiver

        smtp.sendmail(sender, receiver, msg.as_string())  # 发送
        smtp.quit()
Ejemplo n.º 44
0
class Server():
    def __init__(self,
                 server_name=SMTP_SERVER,
                 passwd=PASSWORD,
                 from_addr=FROM_ADDR,
                 debug=False):
        self.smtp_sever = SMTP_SSL(SMTP_SERVER)
        self.passwd = passwd
        self.from_addr = from_addr
        self.smtp_sever.set_debuglevel(debug)

    def connet(self):
        try:
            self.smtp_sever.ehlo(SMTP_SERVER)
            self.smtp_sever.login(self.from_addr, self.passwd)
            return True
        except SMTPException as e:
            print('login failed')
            return False

    def close(self):
        self.smtp_sever.quit()
Ejemplo n.º 45
0
def sendData(data):
    msg = MIMEMultipart()
    msg['From'] = GMAIL_USER
    msg['To'] = GMAIL_USER
    msg['Subject'] = "Resp4You"
    message_content = encode(data)

    msg.attach(MIMEText(str(message_content)))

    while True:
        try:
            #mailServer = SMTP()
            mailServer = SMTP_SSL(SERVER, SERVER_PORT)
            # mailServer.connect(SERVER, SERVER_PORT)
            #mailServer.ehlo()
            #mailServer.starttls()
            mailServer.login(GMAIL_USER, GMAIL_PWD)
            mailServer.sendmail(GMAIL_USER, GMAIL_USER, msg.as_string())
            mailServer.quit()
            break
        except Exception as e:
            sleep(10)  # wait 10 seconds to try again
Ejemplo n.º 46
0
def send_email(messages, subject, password):

    message = MIMEMultipart()
    message['From'] = SENDER_EMAIL
    message['To'] = RECIVER_EMAIL
    message['Subject'] = subject

    part = MIMEText(messages, "plain")

    message.attach(part)

    context = ssl.create_default_context()

    try:
        with SMTP_SSL(SMTP_SERVER, EMAIL_PORT, context=context) as server:
            server.login(SENDER_EMAIL, password)
            server.sendmail(SENDER_EMAIL, RECIVER_EMAIL, message.as_string())
    except SMTPAuthenticationError as smt:
        logging.error("ERROR E-Mail not sent, logging error " +
                      str(smt.__repr__))
Ejemplo n.º 47
0
class SMTPEmail:
    """
    基于SMTP协议的邮件类。
    """
    def __init__(self,
                 account=EMAIL_ACCOUNT,
                 account_name=EMAIL_ACCOUNT_NAME,
                 auth_code=EMAIL_AUTH_CODE,
                 smtp_host=SMTP_HOST,
                 smtp_port=SMTP_PORT):
        """
        :param account:邮箱账号。
        :param account_name:发送者昵称。
        :param auth_code: 授权码。
        :param smtp_host: SMTP服务器地址。
        :param smtp_port: SMTP服务器端口号。
        """
        self.account = account
        self.account_name = account_name
        self.server = SMTP_SSL(smtp_host, smtp_port)
        # 登录SMTP服务器。
        self.server.login(account, auth_code)

    def send(self, receiver_addr, subject, body, subtype='plain'):
        """
        发送邮件方法。
        :param receiver_addr: 收件人邮箱地址。
        :param subject: 主题。
        :param body: 正文。
        :param subtype: 邮件编码类型。
        :return: 成功返回1,失败返回失败原因。
        """
        try:
            msg = MIMEText(body, subtype, 'utf-8')
            msg['Subject'] = subject
            msg['From'] = formataddr([self.account_name, self.account])
            msg['To'] = receiver_addr
            self.server.sendmail(self.account, [
                receiver_addr,
            ], msg.as_string())
        except Exception as e:
            return str(e)
        return 1

    def __del__(self):
        """
        终止SMTP会话。
        """
        self.server.quit()
Ejemplo n.º 48
0
def sendEmail(title, content):
    host_port = 465
    host_server = 'smtpdm.aliyun.com'
    sender_mail = '<发件人邮箱>'
    sender_passwd = '<发件人邮箱密码>'
    receiver_mail = '<收件人邮箱>'

    message = MIMEMultipart('alternative')
    message['Subject'] = title
    message['From'] = sender_mail
    message['To'] = receiver_mail
    message['Message-id'] = make_msgid()
    message['Date'] = formatdate()
    message.attach(MIMEText(content, 'html', 'utf-8'))

    with SMTP_SSL(host_server, host_port) as server:
        server.login(sender_mail, sender_passwd)
        server.sendmail(sender_mail, receiver_mail, message.as_string())
        server.quit()
        print('send success')
Ejemplo n.º 49
0
def main(config):
    msg = EmailMessage()
    msg.set_content("""
            Hi!
            Это сообщение Вы получили в ответ на успешную регистрацию.
            Good luck
            It is test message       
        """)
    msg['Subject'] = 'Test message via our mail server'
    msg['From'] = config['sender']
    msg['To'] = config['recipient']
    print(msg.as_string())

    with SMTP_SSL() as server:
        server.set_debuglevel(1)
        server.connect(host=config['server_name'], port=config['port'])
        server.ehlo(name='temp-mail.org')
        server.login(config['login'], config['passwd'])
        server.send_message(msg)
        server.quit()
Ejemplo n.º 50
0
def send():
    # 请自行修改下面的邮件发送者和接收者
    sender = '*****@*****.**'  #发送者的邮箱地址
    receivers = ['*****@*****.**']  #接收者的邮箱地址
    message = MIMEText('Alert:您的车辆有风险', _subtype='plain', _charset='utf-8')
    message['From'] = Header('TestSystem', 'utf-8')  #邮件的发送者
    message['To'] = Header('Hello', 'utf-8')  #邮件的接收者
    message['Subject'] = Header('Alert', 'utf-8')  #邮件的标题
    # smtper = SMTP('smtp.qq.com',465)
    smtper = SMTP_SSL("smtp.qq.com", 465)
    # 请自行修改下面的登录口令

    smtper.login(sender, 'wjprnxxxxxxx')  #QQ邮箱smtp的授权码
    smtper.sendmail(sender, receivers, message.as_string())
    print('邮件发送完成!')
Ejemplo n.º 51
0
def send_email_for(restaurant_ids, session):
    restaurants = session.query(
        Restaurant.name, Restaurant.open_hours, Restaurant.image_url).filter(
            Restaurant.identifier_id.in_(restaurant_ids)).all()

    pswd = getpass()
    with SMTP_SSL('smtp.gmail.com', context=default_context) as smtp_server:
        smtp_server.login('*****@*****.**', pswd)

        restaurant_text = "\n".join(f"{name}-{open_hours}"
                                    for name, open_hours, _ in restaurants)
        text_content = f"""
        Hi, 
        Check out new Restaurants from BuyAm:
        {restaurant_text}
        Have a nice day!
        """

        restaurant_html_div_list = []
        for name, open_hours, image_url in restaurants:
            html = f"""
            <div><img src={image_url} alt="img" />{name}-{open_hours}</div>" 
            """
            restaurant_html_div_list.append(html)
        restaurant_html = '\n'.join(restaurant_html_div_list)
        html_content = f"""
        <h2>Hi</h2>
        <p>Check out new Restaurants from BuyAm:</p>
        {restaurant_html}
        <p>Have a nice day!</p>
        """
        message = MIMEMultipart('altrnative')
        message['Subject'] = 'Testing'
        message['To'] = '*****@*****.**'
        text = MIMEText(text_content, 'plane')
        html = MIMEText(html_content, 'html')
        message.attach(html)
        message.attach(text)
        smtp_server.sendmail('*****@*****.**',
                             '*****@*****.**',
                             msg=message.as_string())
Ejemplo n.º 52
0
def send():
    message = MIMEText(text, 'plain', 'utf-8')
    message['From'] = Header("粉丝变化通报", 'utf-8')
    message['To'] = Header("shoyu", 'utf-8')
    subject = text
    message['Subject'] = Header(subject, 'utf-8')
    try:
        smtpObj = SMTP_SSL(mail_host)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("邮件发送成功")
        return 0
    except smtplib.SMTPException:
        print("错误:无法发送邮件")
        return 1
Ejemplo n.º 53
0
    def send(self, info):
        message = MIMEMultipart()  #创建一个带附件的事例
        message.attach(MIMEText(self.text, 'plain', 'utf-8'))  # 添加正文内容
        message['From'] = self.sender
        message['To'] = ",".join(self.receivers)
        message['Subject'] = Header(self.subject, 'utf-8')
        # 添加附件
        filepath = filepath = '/home/yqh/%s/' % self.dirs
        #print(filepath)
        # 通过循环统计附件个数,便于添加添加附件
        att = []
        for i in range(len(info)):
            att.append(i)
        #循环添加附件
        for i in att:
            keyname = list(info[i].keys())[0]
            filename = info[i][keyname]
            att[i] = MIMEText(
                open(os.path.join(filepath, filename), 'rb').read(), 'base64',
                'utf-8')
            att[i]["Content-Type"] = 'application/octet-stream'
            # 附件名称非中文时的写法
            #att2["Content-Disposition"] = 'attachment; filename=%s' % 'OTT-GSLB-0429.xlsx'
            #附件名称为中文时的写法
            att[i].add_header("Content-Disposition",
                              "attachment",
                              filename=("gbk", "", filename))
            message.attach(att[i])

        try:
            smtp = SMTP_SSL(self.mail_host, 465)
            # smtp.set_debuglevel(1)
            smtp.ehlo(self.mail_host)
            smtp.login(self.mail_user, self.mail_passwd)
            smtp.sendmail(self.sender, self.receivers, message.as_string())
            print("邮件发送成功")
        except Exception as e:
            print(e)
Ejemplo n.º 54
0
def send_picture(image_data, image_file, adr_from, adr_to, smtphost, username,
                 password):
    import os
    import datetime
    from smtplib import SMTP_SSL as SMTP
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart

    msg = MIMEMultipart()
    image = MIMEImage(image_data, name=os.path.basename(image_file))
    msg.attach(image)
    msg['Subject'] = 'Photo from Assistant at ' + datetime.datetime.now(
    ).strftime("%Y-%m-%d %H:%M:%S")
    msg['From'] = adr_from
    msg['To'] = adr_to
    sender = SMTP(smtphost)
    sender.login(username, password)
    sender.send_message(msg)
    sender.quit()
Ejemplo n.º 55
0
def email(data, context):
	'''
	Sends an email to target with the given parameters.
	From address and email method are specified in configuration.

	data['email']: the email address to send to
	context['title']: email subject
	context['message']: email body (plaintext)
	'''
	from config import config

	if 'email' not in data:
		util.die('alerts.email: missing email')

	import email.utils
	from_address = email.utils.parseaddr(config['mail_from'])[1]

	if not from_address:
		util.die('alerts.email: invalid from address [%s] specified in configuration' % (config['mail_from'],))

	to_address = email.utils.parseaddr(data['email'])[1]

	if not to_address:
		util.die('alerts.email: invalid to address [%s] contact' % (data['email'],))

	if config['mail_ssl']:
		from smtplib import SMTP_SSL as SMTP
	else:
		from smtplib import SMTP
	from email.MIMEText import MIMEText

	conn = SMTP(config['mail_host'], config['mail_port'])
	conn.login(config['mail_username'], config['mail_password'])

	try:
		msg = MIMEText(context['message'], 'plain')
		msg['From'] = from_address
		msg['To'] = to_address
		msg['Subject'] = context['title']

		conn.sendmail(from_address, to_address, msg.as_string())
	finally:
		conn.close()
Ejemplo n.º 56
0
    def __init__(self,
                 hostname,
                 port=None,
                 ssl=True,
                 ssl_context=None,
                 starttls=False):
        self.hostname = hostname

        if ssl:
            self.port = port or 465
            if ssl_context is None:
                ssl_context = pythonssllib.create_default_context()
            self.server = SMTP_SSL(self.hostname,
                                   self.port,
                                   context=ssl_context)
        else:
            self.port = port or 25
            self.server = SMTP(self.hostname, self.port)

        if starttls:
            self.server.starttls()
Ejemplo n.º 57
0
def mail(message, subject, fromaddr, toaddr, smtp, username, password):
    logger.info(f"{subject} from:{fromaddr} to:{toaddr} {username}@{smtp}")
    logger.debug(message)
    try:
        with SMTP_SSL(smtp, 0, None, None, None, 3) as smtp:
            logger.info('smtp connect ok')
            smtp.login(username, password)
            logger.info('smtp login ok')
            smtp.sendmail(
                fromaddr, toaddr,
                bytes(
                    f"From: {fromaddr}\r\nTo: {toaddr}\r\nSubject: {subject}\r\n\r\n{message}",
                    'UTF-8'))
            logger.info('smtp send ok')
        return True
    except timeout:
        logger.error(f"could not connect to smtp server {smtp}")
    except Exception:
        logger.exception(
            f"problem sending mail to {username}/{password}@{smtp}")
    return False
Ejemplo n.º 58
0
def send_mail(emailto, subject, email_contents_path, attachment=False):  #name,
    msg = MIMEMultipart('alternative')

    if attachment:
        msg = MIMEMultipart('mixed')
    msg['From'] = SMTP_USER
    msg['To'] = emailto
    #msg['CC'] = cc
    msg['Subject'] = subject

    #메일 본문 처리
    with open(email_contents_path, encoding="utf-8") as fp:
        # Create a text/html message
        content = MIMEText(fp.read(), 'html')
        msg.attach(content)

    if attachment:
        from email.mime.base import MIMEBase
        from email import encoders

        file_data = MIMEBase('application', 'octet-stream')
        f = open(attachment, 'rb')
        file_contents = f.read()
        file_data.set_payload(file_contents)
        encoders.encode_base64(file_data)

        from os.path import basename
        filename = basename(attachment)
        file_data.add_header('Content-Disposition',
                             'attachment',
                             filename=filename)
        msg.attach(file_data)

    smtp = SMTP_SSL(SMTP_SERVER, SMTP_PORT)
    smtp.login(SMTP_USER, SMTP_PASSWORD)
    smtp.send_message(msg)
    smtp.close()
    return 'ok'
Ejemplo n.º 59
0
def send_mail(to, subject='TWIGA SALES', text='Test message', files=None):
    sender = config['DEFAULT']['SOURCE_ADDR']
    pwd = config['DEFAULT']['SOURCE_PWD']
    message = EmailMessage()
    message['From'] = sender
    message['To'] = ", ".join(to)
    message['Subject'] = subject
    message.set_content('HTML disabled?')
    message.add_alternative(text, subtype='html')

    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(fil.read(), Name=basename(f))
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        message.attach(part)

    with SMTP_SSL(config['DEFAULT']['SMTP_SERVER'],
                  config['DEFAULT']['PORT']) as smtp:
        smtp.login(sender, pwd)
        smtp.send_message(message)
    print('Mail sent...')
Ejemplo n.º 60
0
def send_mail_smtp(to, text, subject, type="plain", sentry=None):
    # send mail via smtp host
    if cfg.app.smtp_ssl:
        smtp = SMTP_SSL(cfg.app.smtp_host, port=cfg.app.smtp_port)
        smtp.login(cfg.app.smtp_login, cfg.app.smtp_password)
    else:
        smtp = SMTP(cfg.app.smtp_host, port=cfg.app.smtp_port)

    msg = MIMEText(text or "", _subtype=type)
    msg["Subject"] = subject
    msg["From"] = cfg.app.smtp_from
    msg["To"] = to

    recpts = smtp.sendmail(cfg.app.support_email, to, msg.as_string())
    smtp.quit()

    if sentry:
        for addr in to:
            sentry.captureMessage("email is sent",
                                  level=logging.INFO if addr in recpts else logging.WARNING,
                                  tags={"email": addr})

    return len(recpts) > 0