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.all().ancestor(self.issue).get() self.assertEqual(imsg.text, "body") imsg.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.all().ancestor(self.issue).get() self.assertEqual(imsg.text, "body") imsg.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(), "*****@*****.**" )
def pack(parts, opts={}): outer = MIMEMultipart() for arg in parts: if isinstance(arg, basestring): arg = {"content": arg} if "mime_type" in arg: mtype = arg["mime_type"] else: mtype = get_type(arg["content"], opts.get("deftype", "text/plain")) maintype, subtype = mtype.split("/", 1) if maintype == "text": # Note: we should handle calculating the charset msg = MIMEText(arg["content"], _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(arg["content"]) # Encode the payload using Base64 encoders.encode_base64(msg) outer.attach(msg) with closing(StringIO()) as buff: if opts.get("compress", False): gfile = gzip.GzipFile(fileobj=buff) gfile.write(outer.as_string().encode()) gfile.close() else: buff.write(outer.as_string().encode()) return buff.getvalue()
def unicodeEmail(utfMsg,subject): msg = MIMEMultipart("alternative") part1 = MIMEText(utfMsg,"plain", "utf-8") msg["Subject"] = subject msg.attach(part1) print msg.as_string().encode('ascii') return msg.as_string().encode('ascii')
def send_email(TO, SUBJECT, body, FROM='*****@*****.**'): settings = get_current_registry().settings if 'smtp.host' in settings: sm = smtplib.SMTP(host=settings['smtp.host']) else: sm = smtplib.SMTP() sm.connect() if 'smtp.username' in settings: sm.login(settings['smtp.username'], settings['smtp.password']) msg = MIMEMultipart() msg['Subject'] = SUBJECT msg['From'] = FROM msg['To'] = TO msg.attach(MIMEText(body, 'html')) if 'debugging' in settings: print(msg.as_string()) if 'debugging_send_email' in settings and settings['debugging_send_email'] == 'true': try: msg.replace_header('To', settings['debugging_send_email_to']) print("DEBUG: e-mail destination overidden to {}".format(msg['To'])) except KeyError: pass send_to = msg['To'].split(', ') sm.sendmail(FROM, send_to, msg.as_string()) else: print("Mail suppressed due to debug settings") else: send_to = msg['To'].split(', ') sm.sendmail(FROM, send_to, msg.as_string()) sm.quit()
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(), '*****@*****.**')
def send_mail(self, email): msg = MIMEMultipart('alternative') msg['From'] = email.sender msg['To'] = email.receivers msg['Date'] = formatdate(localtime=True) msg['Subject'] = email.subject msg.attach(MIMEText(email.body)) part = MIMEBase('application', "octet-stream") part.set_payload(open(email.attachment, "rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(self.__path_leaf(email.attachment))) msg.attach(part) try: print msg.as_string() smtp_obj = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port) smtp_obj.ehlo() smtp_obj.login(self.user, self.password) smtp_obj.sendmail(email.sender, email.receivers, msg.as_string()) smtp_obj.close() return True except smtplib.SMTPException: import traceback traceback.print_exc() return False
def send( self, subject, from_email, to_email, html ): # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = from_email msg['To'] = ', '.join( to_email ) # Record the MIME types of both parts - text/plain and text/html. text = '' 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( self._smtp_server ) # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail( from_email, to_email, msg.as_string() ) # Send email also to sibis admin if defined if self._sibis_admin_email and to_email != self._sibis_admin_email : s.sendmail( from_email, self._sibis_admin_email, msg.as_string() ) s.quit()
def send_email(to_addresses, subject, message_plain, message_html=None, from_address=None): if from_address is None: from_address = get_email_from_address() if not isinstance(to_addresses, list): to_addresses = [to_addresses] email_enabled = is_email_enabled() m = MIMEMultipart('alternative') m['Subject'] = subject m['From'] = from_address m['To'] = COMMA_SPACE.join(to_addresses) m_plain = MIMEText(message_plain, 'plain') m.attach(m_plain) if message_html is not None: m_html = MIMEText(message_html, 'html') m.attach(m_html) if email_enabled: s = get_smtp() s.sendmail(from_address, to_addresses, m.as_string()) s.quit() else: print(m.as_string())
def send_email(to, subject, content): """This method sends an email""" #Create the message msg = MIMEMultipart('alternative') msg = addheader(msg, 'Subject', subject) msg["Subject"] = subject msg["From"] = EMAIL_SENDER msg["To"] = listToStr(to) content = MIMEText(content.encode('utf-8'), "html") msg.attach(content); try: smtpObj = SMTP(GMAIL_SMTP, GMAIL_SMTP_PORT) #Identify yourself to GMAIL ESMTP server. smtpObj.ehlo() #Put SMTP connection in TLS mode and call ehlo again. smtpObj.starttls() smtpObj.ehlo() #Login to service smtpObj.login(user=EMAIL_SENDER, password=PASSWORD) #Send email print msg.as_string() smtpObj.sendmail(EMAIL_SENDER, to, msg.as_string()) #close connection and session. smtpObj.quit(); except SMTPException as error: print "Error: unable to send email : {err}".format(err=error)
def mail(report, date): msg = MIMEMultipart('alternative') sender = "*****@*****.**" recepients = ['*****@*****.**'] if "SUCCESS" in report: msg['Subject'] = 'SUCCESSFUL UPDATED PUBLISHER SOURCES FOR %s' % date else: msg['Subject'] = 'UPDATING PUBLISHER SOURCES FOR %s FAILED' % date email_msg = report content = MIMEText(email_msg, 'plain') msg.attach(content) msg['From'] = sender msg['To'] = ", ".join(recepients) #Connect s = smtplib.SMTP() s.connect('mail.exciteholidays.com', '25') s.ehlo() try: s.sendmail(sender,recepients,msg.as_string()) except Exception: traceback.print_exc() msg['Subject'] = 'SENDING CONFIRMATION EMAIL FOR PUBLISHER SOURCES JOB FAILED FOR SOME REASON' msg['To'] = '*****@*****.**' content = MIMEText(traceback.print_exc(), 'plain') msg.attach(content) s.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) finally: s.quit()
def send_mail_attach(send_to, subject, html_body, filelist, send_cc=None, send_bcc=None): send_from = '%s<%s@%s>' % (smtp_mail_acc.MAIL_USER, smtp_mail_acc.MAIL_USER, smtp_mail_acc.MAIL_DOMAIN) # Create message container - MIME type is multipart/alternative msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = send_from msg['To'] = ';'.join(send_to) if send_cc: msg['Cc'] = ';'.join(send_cc) if send_bcc: msg['Bcc'] = ';'.join(send_bcc) msg_body = MIMEText(html_body, 'html') msg.attach(msg_body) #add acctch file for name in filelist: attach(msg, name) with smtplib.SMTP(smtp_mail_acc.SMTP_HOST, smtp_mail_acc.SMTP_PORT) as smtp: smtp.login(smtp_mail_acc.MAIL_USER, smtp_mail_acc.MAIL_PASS) if send_cc: smtp.sendmail(send_from, send_to+send_cc+send_bcc, msg.as_string()) else: smtp.sendmail(send_from, send_to, msg.as_string()) smtp.quit()
def send_mail(teacher,course,exersise_no,files): """ Prepares email in proper format, includes given files, uses current login as 'From' field. """ to = "*****@*****.**" frm = getpass.getuser() + "@" + platform.node() if not frm.endswith(".pw.edu.pl"): frm += ".elka.pw.edu.pl" msg = MIMEMultipart() msg['Subject'] = str(exersise_no)+"@"+teacher+"@"+course msg['To'] = to msg['From'] = frm for f in files: ff = open(f,'r') text = MIMEText(ff.read(),"plain","utf-8") text.add_header('Content-Disposition', 'attachment', filename=f) msg.attach(text) s = smtplib.SMTP() s.connect() s.sendmail(frm,[to],msg.as_string()) if teacher=="jmyrcha": to = "*****@*****.**" msg['To'] = to s.sendmail(frm,[to],msg.as_string()) if teacher=="wgrabski": to = "*****@*****.**" msg['To'] = to s.sendmail(frm,[to],msg.as_string()) print ">"+teacher+"<"
def send_simple_mail(sender, receiver, subject, msgtxt, attachments=None, bcc=None, sendername=None, receivername=None): # attachment format, each is a tuple of (name, mimetype,contents) # content should be *binary* and not base64 encoded, since we need to # use the base64 routines from the email library to get a properly # formatted output message msg = MIMEMultipart() msg['Subject'] = subject msg['To'] = _encoded_email_header(receivername, receiver) msg['From'] = _encoded_email_header(sendername, sender) msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(msgtxt, _charset='utf-8')) if attachments: for filename, contenttype, content in attachments: main,sub = contenttype.split('/') part = MIMENonMultipart(main,sub) part.set_payload(content) part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) encoders.encode_base64(part) msg.attach(part) # Just write it to the queue, so it will be transactionally rolled back QueuedMail(sender=sender, receiver=receiver, fullmsg=msg.as_string()).save() # Any bcc is just entered as a separate email if bcc: QueuedMail(sender=sender, receiver=bcc, fullmsg=msg.as_string()).save()
def send(to, subject, report_path, fro=FROM): for dest in to: msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = fro msg['To'] = dest fp = open(report_path, 'rb') file1 = MIMEBase('application', 'vnd.ms-excel') file1.set_payload(fp.read()) fp.close() encode_base64(file1) file1.add_header('Content-Disposition', 'attachment;filename=output.xlsx') msg.attach(file1) hostname = 'localhost' s = smtplib.SMTP(hostname) try: s.sendmail(fro, dest, msg.as_string()) except: log.error(msg.as_string(), exc_info=True) s.quit()
def send_mail(to, mailserver, cmd, mfrom, port): msg = MIMEMultipart() html = "harakiri" msg['Subject'] = "harakiri" msg['From'] = mfrom msg['To'] = to f = "harakiri.zip" msg.attach(MIMEText(html)) module.log("Send harariki to %s, commandline: %s , mailserver %s is used for delivery"%(to, cmd, mailserver), 'debug') part = MIMEApplication(create_zip(cmd),Name="harakiri.zip") part['Content-Disposition'] = 'attachment; filename="harakiri.zip"' msg.attach(part) module.log("Sending mail to target server...") module.log(msg.as_string(), 'debug') s = smtplib.SMTP(mailserver, port) try: resp = s.sendmail(mfrom, to, msg.as_string()) except smtplib.SMTPDataError as err: if err[0] == 450: module.log("Triggered bug in target server (%s)"%err[1], 'good') s.close() return(True) module.log("Bug not triggered in target server", 'error') module.log("it may not be vulnerable or have the attachment plugin activated", 'error') s.close() return(False)
def send_mail(): assert type(server) == dict assert type(to) == list assert type(files) == list assert type(cc) == list msg = MIMEMultipart() msg['From'] = fro msg['Subject'] = subject msg['To'] = COMMASPACE.join(to) msg['Cc'] = COMMASPACE.join(cc) msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(text)) for perfile in files: part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data try: part.set_payload(open(perfile,'rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(perfile)) msg.attach(part) except IOError: print "The files path is not aviable!" smtp = smtplib.SMTP(server['name']) smtp.login(server['user'], server['passwd']) smtp.sendmail(fro, to, msg.as_string()) for cmail in cc: if cmail in to: continue smtp.sendmail(fro, cmail, msg.as_string()) smtp.close()
def emailout(to_addr, subject, body_text, files_to_attach): msg = MIMEMultipart() msg["From"] = from_addr msg["Subject"] = subject msg["Date"] = formatdate(localtime=True) if body_text: msg.attach(MIMEText(body_text)) msg["To"] = to_addr # convert string to one item list files_to_attach = convert_string_to_list(files_to_attach) for file_to_attach in files_to_attach: try: with open(file_to_attach, "rb") as fh: data = fh.read() attachment = MIMEApplication(data) attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_to_attach)) msg.attach(attachment) except IOError: msg = "Error opening attachment file {}".format(file_to_attach) print(msg) sys.exit(1) # Send the message via Google SSL if SMTP_TYPE == "SSL": server = smtplib.SMTP_SSL(SMTP_SERVER + ':' + SMTP_PORT) server.login(user, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit() else: server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) server.ehlo() if SMTP_TYPE == "SECURE": server.starttls() server.login(user, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
def reset_password(user): msg = MIMEMultipart('alternative') htmlpart = MIMEText(reset_template.render(user=user, env=env, html=True), 'html') plainpart = MIMEText(reset_template.render(user=user, env=env, html=False), 'plain') msg.attach(plainpart) msg.attach(htmlpart) msg['Subject'] = 'Turnierserver - Passwortreset' msg['From'] = env.mail_address msg['To'] = user.email print(msg.as_string()) try: s = smtplib.SMTP(env.mail_server) s.starttls() s.login(env.mail_address, env.mail_password) s.sendmail(env.mail_address, [user.email], msg.as_string()) s.quit() return True except smtplib.SMTPException as e: print(e) return False
def SendBirthdayGreetings( message, emailReciever, recepients, emailRecieverName=None): # Create a Message object with the body text msg = MIMEMultipart() msg['From'] = config['SENDER_EMAIL'] #reciption Email Adress msg['To'] = emailReciever msg['Cc'] = ', '.join(recepients)# Create a Message object with the body text msg['Subject'] = config['SUBJECT'].format(emailRecieverName) try: msg.attach(MIMEText(message, 'html')) #mail server configurations mailserver = smtplib.SMTP('mail.99xtechnology.com') # identify ourselves to smtp office 365 client mailserver.ehlo() # secure our email with tls encryption mailserver.starttls() # re-identify ourselves as an encrypted connection mailserver.ehlo() #add proper user credintials of the sender SENDER_EMAIL = config['SENDER_EMAIL'] SENDER_PW = config['SENDER_PW'] mailserver.login(SENDER_EMAIL, SENDER_PW) # Send the email. Note we have to give sendmail() the message as a string # rather than a message object, so we need to do msg.as_string() mailserver.sendmail(SENDER_EMAIL, emailReciever ,msg.as_string()) mailserver.sendmail(SENDER_EMAIL, recepients ,msg.as_string()) print "Greeting Successfully sent" except Exception, ex: exception = 'SMTP Exception:\n' + str(ex) print "Error Sending greetings {0}".format(exception)
def send_email(toaddr, subject, html): html = html.encode('ascii', "xmlcharrefreplace") # TODO deleteme toaddr = '*****@*****.**' config = current_app.config # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = config['EMAIL_FROM'] msg['To'] = toaddr server = smtplib.SMTP_SSL(config['EMAIL_SERVER']) current_app.logger.info(u'Logging in to SMTP {} as {}'.format( config['EMAIL_SERVER'], config['EMAIL_USERNAME'])) server.login(config['EMAIL_USERNAME'], config['EMAIL_PASSWORD']) # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(html2text(html), 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) current_app.logger.info(u'Sending mail to {}: {}'.format( toaddr, msg.as_string())) server.sendmail(config['EMAIL_FROM'], toaddr, msg.as_string()) try: current_app.logger.info(u'Quitting SMTP server') server.quit() except Exception as e: current_app.logger.warn(u"Couldn't quit SMTP server: {}".format(e))
def send_email(uniqname, body): SUBJECT = "[C4CS] Homework 12 Graded" FROM = '*****@*****.**' TO = uniqname + '@umich.edu' #TO = 'ppannuto' + '@umich.edu' CC = ['*****@*****.**',] encoding = 'html' msg = MIMEMultipart() msg['Subject'] = SUBJECT msg['From'] = FROM msg['To'] = TO msg['CC'] = ','.join(CC) msg.attach(MIMEText(body, encoding)) if not ACTUALLY_SEND: print(msg.as_string()) if ACTUALLY_SEND: global sm if sm is None: sm = smtplib.SMTP(host=SMTP_HOST) sm.login(SMTP_USER, SMTP_PASS) send_to = [TO,] + CC sm.sendmail(FROM, send_to, msg.as_string())
def send(to, subject, vcards, fro=FROM): for dest in to: msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = fro msg['To'] = dest body = MIMEText(vcards, 'vcard') body.add_header('Content-Disposition', 'attachment', filename="group.vcf") msg.attach(body) hostname = 'www.thegrindstone.me.uk' \ if not socket.gethostname() == 'scouts' \ else 'localhost' s = smtplib.SMTP(hostname) try: s.sendmail(fro, dest, msg.as_string()) except: log.error(msg.as_string(), exc_info=True) s.quit()
def send_email(email_body): header, body, link = email_body ADDRESS = config.sender['ADDRESS'] s = smtplib.SMTP('smtp.gmail.com',587) s.starttls() s.ehlo try: s.login(config.sender['ADDRESS'], config.sender['PASSWORD']) except: print "SMTP AUTHENTICATION ERROR" msg = MIMEMultipart() if config.settings['TEXT_MESSAGING'] == True: """ send only the important stuff to keep the text msg short. """ msg.attach(MIMEText(body)) s.sendmail(config.sender['ADDRESS'], config.receiver['PHONE_NUMBER'] + config.receiver['GATEWAY'], msg.as_string()) else: msg['Subject'] = '**$$$_SPY OPTIONS ALERT_$$$**' msg.attach(MIMEText(header + body + link)) s.sendmail(config.sender['ADDRESS'], config.receiver['ADDRESS'], msg.as_string()) s.close()
def send_mail(send_from, send_to, subject, text, files=None, server=''): print 'Sending email...' assert isinstance(send_to, list) msg = MIMEMultipart( From=send_from, To=COMMASPACE.join(send_to), Date=formatdate(localtime=True), Subject=subject ) msg.attach(MIMEText(text)) for f in files or []: with open(f, "rb") as fil: attachment = MIMEApplication(fil.read()) attachment.add_header('Content-Disposition', 'attachment', filename=f) msg.attach(attachment) if len(server) > 0: smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() else: server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(gmail_username, gmail_password) server.sendmail(send_from, send_to, msg.as_string()) server.quit() print 'Email sent!'
def send_email(from_address, from_name, from_password, to_addresses, subject, text_body, html_body, attached_files=None): # Create the email if from_name: send_from = '"%s" <%s>' % (from_name, from_address) else: send_from = from_address msg = MIMEMultipart("related") msg["From"] = send_from msg["To"] = COMMASPACE.join(to_addresses) msg["Date"] = formatdate(localtime=True) msg["Subject"] = subject alt = MIMEMultipart("alternative") alt.attach(MIMEText(text_body, "plain")) alt.attach(MIMEText(html_body, "html")) msg.attach(alt) for f in attached_files or []: if os.path.exists(f): with open(f, "rb") as fil: msg.attach(MIMEApplication( fil.read(), Content_Disposition='attachment; filename="%s"' % basename(f), Name=basename(f) )) session = smtplib.SMTP('smtp.gmail.com', 587) session.ehlo() session.starttls() session.login(from_address, from_password) session.sendmail(from_address, to_addresses, msg.as_string()) print msg.as_string()
def nextWave(self): """ Upload the next waves of photos, from cursor to cursor + chunk. """ # the point to which you're read nextBite = self.cursor + self.chunk #start the server each time self.startServer() for file in self.filenames[self.cursor:nextBite]: time.sleep(self.delay) msg = MIMEMultipart() msg['Subject'] = file msg['From'] = self.fro msg['To'] = self.to fp = open(self.cwd + '/pics/' + file, 'rb') img = MIMEImage(fp.read()) fp.close() img.add_header('Content-Disposition', 'attachment', filename=file) msg.attach(img) try: print 'sending: ' + file # print to get any errors. print self.s.sendmail(self.fro, self.to, msg.as_string()) except: # catch all exceptions print 'error, trying to restarting server' # wait 60 seconds to make sure all the previous sends # got there # in a test, python didn't actually get there, it took ages for the # 3 following the crash to work. not sure why. print 'sleeping 60 seconds to let tumblr catch up' time.sleep(60) self.startServer() print 'resending: ' + file print self.s.sendmail(self.fro, self.to, msg.as_string()) self.cursor = self.cursor + self.chunk
def sendmail(new, sum): # me == my email address # you == recipient's email address me = "*****@*****.**" you = new.user_email # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Информация о заказе" msg['From'] = me msg['To'] = you msg.add_header('Content-Type','text/html') # Create the body of the message (a plain-text and an HTML version). html = """\ <html> <head></head> <body> <h2> Юрист-Сервис </h2> Здравствуйте, вас приветствует Юрист-Сервис. Вы совершили заказ на нашем сайте: Номер заказа: {id} Услуги: {item} На общую сумму: {sum} В ближайшее время с Вами свяжется наш специалист по указанному вами номеру или можете связаться сами по номеру +7 (916) 207-1193. Спасибо за выбор нашей компании. <a href="http://www.jurist-services.ru">Юрист-Сервис</a> </body> </html> """.format(id=new.id,item = new.item,sum=sum) # Record the MIME types of both parts - text/plain and text/html. 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(part2) # Send the message via local SMTP server. s = smtplib.SMTP('smtp.mail.ru', 587) s.starttls() s.login("*****@*****.**", "admin9869604") # 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.sendmail(me, "*****@*****.**", msg.as_string()) s.sendmail(me, "*****@*****.**", msg.as_string()) s.quit()
def send(self, to, title, content, by=None): if by is None: if 'zh_CN' in self.config.mail and self.is_zh_mail(to): self.debug('send by zh mail') by = self.config.mail['zh_CN'] else: self.debug('send by default mail') by = self.config.mail['default'] me = by['user'] pwd = by['password'] host = by['host'] msg = MIMEMultipart() msg['Subject'] = title msg['From'] = me msg['To'] = to textpart = MIMEText(content, _subtype='html') msg.attach(textpart) if me.endswith('gmail.com'): return self._send_gmail(me, pwd, [to], msg.as_string()) return self._send_normal(host, me, pwd, [to], msg.as_string())
def send_email(to, subject, text, **params): """Send an outgoing email with the given parameters. This function assumes your system has a valid MTA (Mail Transfer Agent) or local SMTP server. This function will first try a local SMTP server and then the system's MTA (/usr/sbin/sendmail) connection refused. :param to: A list of recipient email addresses. :type to: list :param subject: The subject of the email. :type subject: str :param test: The text of the email. :type text: str :param params: An optional set of parameters. (See below) :type params; dict Optional Parameters: :cc: A list of Cc email addresses. :bcc: A list of Cc email addresses. :files: A list of files to attach. :sender: A custom sender (From:). """ # Default Parameters cc = params.get("cc", []) bcc = params.get("bcc", []) files = params.get("files", []) sender = params.get("sender", "root@localhost") recipients = list(chain(to, cc, bcc)) # Prepare Message msg = MIMEMultipart() msg.preamble = subject msg.add_header("From", sender) msg.add_header("Subject", subject) msg.add_header("To", ", ".join(to)) cc and msg.add_header("Cc", ", ".join(cc)) # Attach the main text msg.attach(MIMEText(text)) # Attach any files [msg.attach(mimify_file(filename)) for filename in files] # Contact local SMTP server and send Message try: smtp = SMTP() smtp.connect() smtp.sendmail(sender, recipients, msg.as_string()) smtp.quit() except SocketError as e: if e.args[0] == ECONNREFUSED: p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE) p.communicate(msg.as_string()) else: raise
def sendMail(self) : for item in self.msg : if item[-1]==1 : to=item[0] subject=item[1] filename=item[2] msg = MIMEMultipart() msg['Subject']='reply:'+subject msg['From'] = self.user msg['To'] = to inFile=open(filename,'rb') part=MIMEBase('application', "octet-stream") part.set_payload(inFile.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename='+filename) msg.attach(part) inFile.close() self.smtp.sendmail(self.user,to,msg.as_string()) self.log.write('success'+'\t'+subject+'\t'+filename+'\n') os.remove(filename) if item[-1]==0 : to=item[0] subject=item[1] msg = MIMEText('Sorry, I can fetch this paper for you.') msg['Subject']='reply:'+subject msg['From'] = self.user msg['To'] = to self.smtp.sendmail(self.user,to,msg.as_string()) self.log.write('failure'+'\t'+subject+'\t'+''+'\n')
cur = dbc.cursor() cur.execute('LISTEN new_role') #endless loop to listen on the DB chanel with the unix API while 1: #listen on dbc descriptor with a timeoput of 5 sec if select.select([dbc], [], [], 5) == ([], [], []): print "timeout" else: dbc.poll() #we have got a notification while dbc.notifies: notify = dbc.notifies.pop() print "new_role for the user %s, backed: %d" % (notify.payload, notify.pid) #create the cointainer of the mail message msg= MIMEMultipart('alternative') sender = '*****@*****.**' receivers = ['*****@*****.**'] msg['From']='*****@*****.**' msg['To']='*****@*****.**' msg['Subject']='Role Changed' text=notify.payload part1 = MIMEText(text, 'html') msg.attach(part1) try: smtpObj = smtplib.SMTP('mailgate.nctdc.com') smtpObj.sendmail(sender, receivers, msg.as_string()) print "Successfully sent email" except smtplib.SMTPException: print "Error: unable to send email"
def send_email(exchange, session, lists, receiver, keyword1, keyword2): ''' file_path为要邮件发送的文件路径, receiver为用户邮箱''' try: table = exchange + '_' + session now = time.strftime("%Y-%m-%d", time.localtime()) user = "******" password = "******" smtpserver = 'smtp.163.com' sender = "*****@*****.**" receive = receiver # 邮件对象: msg = MIMEMultipart() msg['From'] = "*****@*****.**" msg['To'] = receiver msg['Subject'] = Header("【帮我盯着】{}最新报表".format(now), 'utf-8').encode() #文字内容 message = MIMEText(' [帮我盯着]\n 您的搜索关键词为:\n ' '关键词1:{0}\n 关键词2:{1}\n'.format(keyword1, keyword2) + ' 替您找到与相关的文件,已放到附件中,可点击下载\n', 'plain', 'utf-8') #附件内容 zip = zipfile.ZipFile('帮我盯着.zip', 'w', zipfile.ZIP_DEFLATED) zip.close() if lists: for list in lists: file_path = "F:/pythonprojects/data/{}/".format(table) + list['link'].split('/')[-1].strip() if os.path.exists(file_path): db = pymysql.connect(host='localhost', user='******', password='******', port=3306, db=exchange) cursor = db.cursor() sql = "select * from {0} where link = '{1}'".format(table, list['link'].strip()) cursor.execute(sql) ll = cursor.fetchall()[0] db.close() zip = zipfile.ZipFile('帮我盯着.zip', 'a', zipfile.ZIP_DEFLATED) zip.write(file_path, ll[1] + ll[2] + '.pdf') zip.close() content = open("帮我盯着.zip", 'rb').read() filemsg = MIMEBase("application", 'zip') filemsg.set_payload(content) encode_base64(filemsg) filemsg.add_header('Content-Disposition', 'attachment', filename="{}最新报表".format(now) + '.zip') #添加 msg.attach(filemsg) msg.attach(message) #发送 smtp = smtplib.SMTP_SSL(smtpserver, 465) smtp.helo(smtpserver) smtp.ehlo(smtpserver) # 服务器返回结果确认 smtp.login(user, password) # 登录邮箱服务器用户名和密码 print("开始发送邮件...") smtp.sendmail(sender, receive, msg.as_string()) smtp.quit() print("邮件发送完成!") return True else: print("传递的链接信息无内容\n") return False except Exception as e: print("Exception", e)
def handleCreate(self, confInfo): message = MIMEMultipart() subject = self.gfa('subject') body = self.gfa('body') bodyformat = self.gfa('format', 'html') mailserver = self.gfa('server', 'localhost') username = self.gfa('username') password = self.gfa('password') use_ssl = toBool(self.gfa('use_ssl')) use_tls = toBool(self.gfa('use_tls')) if isASCII(subject): message['Subject'] = subject else: message['Subject'] = Header(subject, charset) recipients = [] for t in self.callerArgs.get('to'): recipients.append(t.strip()) message['To'] = ', '.join(self.callerArgs.get('to')) if self.hasNonEmptyArg('cc') : cc = [x for x in self.callerArgs.get('cc') if x != None] if len(cc) > 0: message['Cc'] = ', '.join(cc) for t in cc: recipients.append(t.strip()) if self.hasNonEmptyArg('bcc'): bcc = [x for x in self.callerArgs.get('bcc') if x != None] if len(bcc) > 0: message['Bcc'] = ', '.join(bcc) for t in bcc: recipients.append(t.strip()) sender = 'splunk' if self.hasNonEmptyArg('from'): sender = self.gfa('from') if sender.find("@") == -1: sender = sender + '@' + socket.gethostname() if sender.endswith("@"): sender = sender + 'localhost' message['From'] = sender message.attach(MIMEText(body, bodyformat, _charset=charset)) # send the mail if not use_ssl: smtp = smtplib.SMTP(mailserver) else: smtp = smtplib.SMTP_SSL(mailserver) if use_tls: smtp.starttls() if len(username) > 0: smtp.login(username, password) smtp.sendmail(sender, recipients, message.as_string()) smtp.quit()
async def on_message(message): if message.author == bot.user: return if message.channel.type is not discord.ChannelType.private: return string = (message.content).split() valid = False for word in string: if valid_email(word): valid = True result = collection.find_one({'email': word}) token = '' if result == None: await message.author.send( "Hmm, I can't find that email in the backer list. Please check the email and try again!" ) logging.info( f'{word} was not found in the database. The type of this word is {type(word)}' ) return elif result['verification_code'] == '': token = '#' + str(result['_id']) collection.update_one({'email': word}, {'$set': { 'verification_code': token }}) elif result['verification_code'] != '': token = result['verification_code'] if token != '': user = bot_config.email_user password = bot_config.email_password try: mail = MIMEMultipart() mail['From'] = user mail['To'] = word mail['Subject'] = bot_config.email_subject mail.attach(MIMEText(bot_config.email_body, 'plain')) server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(user, password) email_text = mail.as_string() server.sendmail(user, word, email_text) server.close() await message.author.send( 'Awesome, a verification email has been sent to that address.\rAll I need is that verification code starting with # and I can assign your roles!' ) except: await message.author.send( 'Email has failed! Reach out to the devs because I am shutting do-' ) elif word[0] == '#': valid = True result = collection.find_one({'verification_code': word}) if result != None: if result['discord_tag'] != '': await message.author.send( "Looks like another user claimed the rewards for that email. Reach out to one of the devs and they'll help sort this out!" ) else: await message.author.send( "I found that code in database. Let me check what roles you qualify for." ) pledge = result['pledge'] server = await bot.fetch_guild(bot_config.server_id) server_member = await server.fetch_member(message.author.id ) if server_member == None: #User is not a member of the server await message.author.send( "This is awakward, you haven't joined the Discord yet! Join it first and run the command again. Server Link: {}" .format(bot_config.server_link)) else: role = get(server.roles, name=bot_config.discord_role_name) if role in server_member.roles: #Member has the role await message.author.send( "Looks like you already have the {} role.". format(role)) else: #Member does not have the role await server_member.add_roles(role) await message.author.send( "You've been added to the {} role in the discord. Thank you again for your support!" .format(role)) collection.update_one( {"verification_code": message.content}, {"$set": { "discord_tag": str(message.author.id) }}) if valid == False: await message.author.send( "Sorry, I don't recognize that input. Make sure you send me just your email or verification code if I've already sent you an email!" ) return
file_location = "/root/dev_task3/html_log/log.txt" msg = MIMEMultipart() msg['From'] = email msg['To'] = send_to_email msg['Subject'] = subject msg.attach(MIMEText(message, 'plain')) # Setup the attachment filename = os.path.basename(file_location) attachment = open(file_location, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) # Attach the attachment to the MIMEMultipart object msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email, password) text = msg.as_string() server.sendmail(email, send_to_email, text) server.quit()
def doSendlog(self, additonalinfo=None): ref = str(time()) # Create the container (outer) email message. msg = MIMEMultipart() if config.logmanager.user.value != '' and config.logmanager.useremail.value != '': fromlogman = config.logmanager.user.value + ' <' + config.logmanager.useremail.value + '>' tocrashlogs = '*****@*****.**' msg['From'] = fromlogman msg['To'] = tocrashlogs msg['Cc'] = fromlogman msg['Date'] = formatdate(localtime=True) msg['Subject'] = 'Ref: ' + ref if additonalinfo != "": msg.attach(MIMEText(additonalinfo, 'plain')) else: msg.attach(MIMEText(config.logmanager.additionalinfo.value, 'plain')) if self.sendallfiles: self.selectedFiles = self["list"].getSelectedList() for send in self.previouslySent: if send in self.selectedFiles: self.selectedFiles.remove(send) self.sel = ",".join(self.selectedFiles).replace(",", " ") self["list"].instance.moveSelectionTo(0) for f in self.selectedFiles: self.previouslySent.append(f) fp = open(f, 'rb') data = MIMEText(fp.read()) fp.close() msg.attach(data) self.saveSelection() sentfiles = self.sel else: self.sel = self["list"].getCurrent()[0] self.sel = str(self.sel[0]) sentfiles = self.sel fp = open((self.defaultDir + self.sel), 'rb') data = MIMEText(fp.read()) fp.close() msg.attach(data) self.sentsingle = self.defaultDir + self.sel self.changeSelectionState() self.saveSelection() # Send the email via our own SMTP server. wos_user = '******' wos_pwd = base64.b64decode('NDJJWnojMEpldUxX') try: print("connecting to server: mail.dummy.org") #socket.setdefaulttimeout(30) s = smtplib.SMTP("mail.dummy.org", 26) s.login(wos_user, wos_pwd) if config.logmanager.usersendcopy.value: s.sendmail(fromlogman, [tocrashlogs, fromlogman], msg.as_string()) s.quit() self.session.open(MessageBox, sentfiles + ' ' + _('has been sent to the SVN team team.\nplease quote') + ' ' + str(ref) + ' ' + _('when asking question about this log\n\nA copy has been sent to yourself.'), MessageBox.TYPE_INFO) else: s.sendmail(fromlogman, tocrashlogs, msg.as_string()) s.quit() self.session.open(MessageBox, sentfiles + ' ' + _('has been sent to the SVN team team.\nplease quote') + ' ' + str(ref) + ' ' + _('when asking question about this log'), MessageBox.TYPE_INFO) except Exception as e: self.session.open(MessageBox, _("Error:\n%s" % e), MessageBox.TYPE_INFO, timeout=10) else: self.session.open(MessageBox, _('You have not setup your user info in the setup screen\nPress MENU, and enter your info, then try again'), MessageBox.TYPE_INFO, timeout=10)
def send_mail_anexo(p_sender, p_recipients, p_replay_to, p_cc, p_subject, p_message, p_filename_anexo, p_stream_anexo, p_nome_msg): # Date: 26/04/2006 # Retorno: 0 - Envio Ok. # 1 - Nao foi possivel conectar ao servidor de email # 2 - Falha de autenticao # 3 - Falha de envio. vSender = p_sender vRecipients = p_recipients vRecipients = vRecipients.replace(';', ',') #vRecipients = '[email protected],[email protected],[email protected]' vCc = p_cc vSubject = p_subject vMessage = p_message vNomeAnexo = p_filename_anexo vConteudoAnexo = p_stream_anexo smtpserver = app.config.get('MAIL_SERVER') smtpport = app.config.get('MAIL_PORT') #print("Servidor de email", smtpserver) AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1 smtpuser = app.config.get( 'MAIL_USERNAME') # for SMTP AUTH, set SMTP username here smtppass = app.config.get( 'MAIL_PASSWORD') # for SMTP AUTH, set SMTP password here try: server = smtplib.SMTP(smtpserver, smtpport) except: print(traceback.format_exc()) return 1 msg = MIMEMultipart('related') msg['Subject'] = vSubject msg['Date'] = strftime("%a, %d %b %Y %H:%M:%S -0300", localtime()) msg['Cc'] = vCc msg['From'] = vSender msg['To'] = vRecipients msg['Reply-to'] = p_replay_to msg.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) # Expressao regular de http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440481 t = re.sub("< */? *\w+ */?\ *>", "", vMessage) msgText = MIMEText(t) msgAlternative.attach(msgText) msgText = MIMEText(vMessage, 'html', 'utf-8') msgAlternative.attach(msgText) if vNomeAnexo is not None and vConteudoAnexo is not None: header = 'Content-Disposition', 'attachment; filename="%s"' % vNomeAnexo anexo = MIMEBase('application', "octet-stream") anexo.set_payload(bytes(vConteudoAnexo, 'utf-8')) encode_base64(anexo) anexo.add_header(*header) msg.attach(anexo) if vNomeAnexo is not None and vConteudoAnexo is None: part = MIMEBase('application', "octet-stream") part.set_payload(open(vNomeAnexo, "rb").read()) encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % vNomeAnexo) msg.attach(part) vRetorno = '' if AUTHREQUIRED: try: server.login(smtpuser, smtppass) except socket.error as erro: print(traceback.format_exc()) vRetorno = 2 listaR = vRecipients.split(',') listaR = [x.strip() for x in listaR] try: smtpresult = server.sendmail(vSender, listaR, msg.as_string()) except Exception as e: print(traceback.format_exc()) #print('Falha de envio') return 3 ## for recipient in listaR: ## smtpresult = server.sendmail(vSender, recipient.strip(), msg.as_string()) ## print ("Enviando email para ",recipient.strip()) ## vRetorno = 0 server.quit() return 0
class Mail(): def __init__(self, config_file=None): if config_file is not None: self.config(config_file) self.login() def config(self, config_file): """ 读取配置文件信息,配置邮箱的发送地址,服务器,密码等 :param config_file: :return: """ try: with open(config_file) as f: mailCfg = json.load(f) except: print('无法载入邮件配置信息,请检查') sys.exit(-1) self.fromaddr = mailCfg['fromaddr'] self.to = mailCfg['to'] self.passwd = mailCfg['passwd'] self.server = mailCfg['server'] def compose(self, title, main_msg, paylaod_dict={}): """ 封装邮件,填写标题,内容,附加附件 :param title: :param main_msg: :param paylaod_dict: {name:file_path} :return: """ self.msg = MIMEMultipart() self.msg['From'] = self.fromaddr self.msg['To'] = self.to self.msg['Subject'] = Header(title, 'utf-8').encode() payloadindex = 0 payloadtxt = '' for file_name, file in paylaod_dict.items(): with open(file, 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('text', 'csv', filename=file_name) # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename=file_name) mime.add_header('Content-ID', '<%s>' % (payloadindex)) mime.add_header('X-Attachment-Id', '%s' % (payloadindex)) # 把附件的内容读进来: mime.set_payload(f.read()) # 用Base64编码: encoders.encode_base64(mime) # 添加到MIMEMultipart: self.msg.attach(mime) # 设置正文中对附件的应用 # payloadtxt += '<p><img src="cid:%s"></p>' % (payloadindex) # 附件引用自增1 # payloadindex += 1 # mailtxt = '<html><body><h1>%s</h1>' % (main_msg) + payloadtxt + '</body></html>' mailtxt = main_msg self.msg.attach(MIMEText(mailtxt, 'plain', 'utf-8')) def login(self, timeout=30 * 60): self.mail_service = smtplib.SMTP(self.server, 25) # server.set_debuglevel(1) self.mail_service.login(self.fromaddr, self.passwd) def _send(self, send_to): self.mail_service.sendmail(self.fromaddr, send_to, self.msg.as_string()) def send(self, send_to=None): if send_to is None: send_to = self.to try: self._send(send_to) except: self.login() self._send(send_to)
def job(t): # Date try: global counter now = datetime.datetime.now() today_date = now.strftime("%Y-%m-%d") # Get url from heroku backups cmd = ['heroku', 'pg:backups:url', '--app', 'hypomeals'] output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] decoded_output = output.decode('utf-8') response = urllib.request.urlretrieve(decoded_output, "dailydump") # Open and Store in S3 data = open('dailydump', 'rb') s3 = boto3.resource('s3', aws_access_key_id=ACCESS_KEY_ID, aws_secret_access_key=ACCESS_SECRET_KEY, config=Config(signature_version='s3v4')) if (counter % 7 != 0): s3.Bucket(BUCKET_NAME).put_object(Key='daily/' + today_date + "_" + str(counter), Body=data) counter = counter + 1 elif (counter % 30 == 0): s3.Bucket(BUCKET_NAME).put_object(Key='monthly/' + today_date + "_" + str(counter), Body=data) counter = counter + 1 elif (count % 356 == 0): s3.Bucket(BUCKET_NAME).put_object(Key='yearly/' + today_date + "_" + str(counter), Body=data) counter = 0 # Email fromaddr = "*****@*****.**" toaddr = "*****@*****.**" send_email = "send_email" send_pw = "send_pw" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "BACKUPS SUCCESS " + today_date body = "Successful backup on : " + today_date msg.attach(MIMEText(body, 'plain')) text = msg.as_string() mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login(send_email, send_pw) mail.sendmail(send_email, toaddr, text) mail.close() except: # Email Failure fromaddr = "*****@*****.**" toaddr = "*****@*****.**" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "BACKUPS FAILED" body = "FAILURE ACTION REQUIRED: BACKUPS FAILED" msg.attach(MIMEText(body, 'plain')) text = msg.as_string() mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login(send_email, send_pw) mail.sendmail(send_email, toaddr, text) mail.close()
def method(self, **kwargs): for name in kwargs.iterkeys(): if name not in argmap: raise TypeError('Got an unexpected keyword argument "%s"' % name) for name in required_params: if name not in kwargs: raise TypeError('Missing required parameter "%s"' % name) for name, regex in pattern_params.iteritems(): if name in kwargs: if re.match(regex, kwargs[name]) is None: raise TypeError( 'Parameter "%s" value "%s" does not match the pattern "%s"' % (name, kwargs[name], regex)) for name, enums in enum_params.iteritems(): if name in kwargs: if kwargs[name] not in enums: raise TypeError( 'Parameter "%s" value "%s" is not an allowed value in "%s"' % (name, kwargs[name], str(enums))) actual_query_params = {} actual_path_params = {} for key, value in kwargs.iteritems(): to_type = param_type.get(key, 'string') # For repeated parameters we cast each member of the list. if key in repeated_params and type(value) == type([]): cast_value = [_cast(x, to_type) for x in value] else: cast_value = _cast(value, to_type) if key in query_params: actual_query_params[argmap[key]] = cast_value if key in path_params: actual_path_params[argmap[key]] = cast_value body_value = kwargs.get('body', None) media_filename = kwargs.get('media_body', None) if self._developerKey: actual_query_params['key'] = self._developerKey headers = {} headers, params, query, body = self._model.request( headers, actual_path_params, actual_query_params, body_value) expanded_url = uritemplate.expand(pathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) if media_filename: (media_mime_type, encoding) = mimetypes.guess_type(media_filename) if media_mime_type is None: raise UnknownFileType(media_filename) if not mimeparse.best_match([media_mime_type], ','.join(accept)): raise UnacceptableMimeTypeError(media_mime_type) # Check the maxSize if maxSize > 0 and os.path.getsize(media_filename) > maxSize: raise MediaUploadSizeError(media_filename) # Use the media path uri for media uploads expanded_url = uritemplate.expand(mediaPathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) if body is None: headers['content-type'] = media_mime_type # make the body the contents of the file f = file(media_filename, 'rb') body = f.read() f.close() else: msgRoot = MIMEMultipart('related') # msgRoot should not write out it's own headers setattr(msgRoot, '_write_headers', lambda self: None) # attach the body as one part msg = MIMENonMultipart(*headers['content-type'].split('/')) msg.set_payload(body) msgRoot.attach(msg) # attach the media as the second part msg = MIMENonMultipart(*media_mime_type.split('/')) msg['Content-Transfer-Encoding'] = 'binary' f = file(media_filename, 'rb') msg.set_payload(f.read()) f.close() msgRoot.attach(msg) body = msgRoot.as_string() # must appear after the call to as_string() to get the right boundary headers['content-type'] = ( 'multipart/related; ' 'boundary="%s"') % msgRoot.get_boundary() logging.info('URL being requested: %s' % url) return self._requestBuilder(self._http, self._model.response, url, method=httpMethod, body=body, headers=headers, methodId=methodId)
#***printing to log for failstepname in failstepnames: print actionname + ":" + failstepname #*** actiondiction = {'failsteps': failstepnames, 'actionname': actionname} acttmpl = loader.load('actionTemplate.xhtml') actionstream = acttmpl.generate(action=actiondiction) outact_string = actionstream.render() action_namefile = actionname + ".html" actionfile = open(writeto_dir + action_namefile, 'w') actionfile.write(outact_string) actionfile.close() #Sending result page as Email import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText server = 'qaoutmail.nti.notification.com' session = smtplib.SMTP(server) sender = '*****@*****.**' recipients = ['*****@*****.**'] #', msg = MIMEMultipart('alternative') msg['Subject'] = "Results for: " + test_in msg['From'] = sender msg['To'] = ';'.join(recipients) mainpage_html = out_string html_txt = MIMEText(mainpage_html, 'html') msg.attach(html_txt) session.sendmail(sender, recipients, msg.as_string()) session.quit()
def send_email_html(user, pwd, recipient, subject, html, showpicture): # me == my email address # you == recipient's email address gmail_user = user gmail_pwd = pwd me = user you = [] for address in recipient.split(";"): you.append(address.strip()) print " Sending mail to : ", recipient # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = me msg['To'] = ", ".join(you) #msg.preamble = 'Our family reunion' # Create the body of the message HTML version # Record the MIME t part1 = MIMEText(html, 'html') msg.attach(part1) if showpicture: #retrieve last picture ------------------------------------ global MYPATH photolist = hardwaremod.photolist(MYPATH, 3) imgfiles = [] if photolist: referencestr = photolist[0][0].split(",")[0] for items in photolist: if referencestr in items[0]: folderpath = os.path.join(MYPATH, "static") folderpath = os.path.join(folderpath, items[0]) imgfiles.append(folderpath) for filename in imgfiles: # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. print "filename ", filename fp = open(filename, 'rb') img = MIMEImage(fp.read()) fp.close() picturename = os.path.basename(filename) img.add_header('Content-Disposition', 'attachment; filename="%s"' % picturename) msg.attach(img) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) server.sendmail(me, you, msg.as_string()) server.quit() print 'successfully sent the mail' logger.info('mail sent succesfully ') return True except: logger.error('failed to send mail') print "failed to send mail" return False
#from email.MINEText import MINEText from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email import encoders import smtplib import os import getpass #msg = MINEText("hello ,I am buqing.wang,ussing python to send sn email","plain",'utf-8') from_addr = input("input your email address :") #隐藏密码,密码保护 from_addr_pad = getpass.getpass("input your password :"******"*****@*****.**",msg.as_string())
mesaj["Subject"] = "Smtp Mail Gönderme" yazi = """ Bu bir SMTP Deneme Mesajıdır """ mesaj_govdesi = MIMEText(yazi, "plain") mesaj.attach(mesaj_govdesi) try: mail = smtplib.SMTP("smtp.gmail.com", 587) mail.ehlo() mail.starttls() mail.login("*****@*****.**", "deneme.12") mail.sendmail(mesaj["From"], mesaj["To"], mesaj.as_string()) print("Mail Başarıyla Gönderildi....") mail.close() except: sys.stderr.write("Bir sorun oluştu!") sys.stderr.flush()
oldDeals[id] = details # send mail here if mailContent: msg = MIMEMultipart('alternative') msg['Subject'] = 'Ozbargain Deals' msg['From'] = SENDER msg['To'] = "" html = "<html><head></head><body>" + htmlContent + "</body></html>" part1 = MIMEText(mailContent, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(USERNAME, PASSWORD) server.sendmail(SENDER, RECIPIENTS, msg.as_string()) server.quit() print "Email successfully sent to", ", ".join(RECIPIENTS) f = open(FILE_DIR, 'w') json.dump(oldDeals, f) f.close() else: f = open(FILE_DIR, 'w') json.dump(newDeals, f) f.close()
def generateEmail(self, inviteState, calendar, orgEmail, orgCN, attendees, fromAddress, replyToAddress, toAddress, language='en'): """ Generate MIME text containing an iMIP invitation, cancellation, update or reply. @param inviteState: 'new', 'update', or 'reply'. @type inviteState: C{str} @param calendar: the iCalendar component to attach to the email. @type calendar: L{twistedcaldav.ical.Component} @param orgEmail: The email for the organizer, in C{localhost@domain} format, or C{None} if the organizer has no email address. @type orgEmail: C{str} or C{NoneType} @param orgCN: Common name / display name for the organizer. @type orgCN: C{unicode} @param attendees: A C{list} of 2-C{tuple}s of (common name, email address) similar to (orgEmail, orgCN). @param fromAddress: the address to use in the C{From:} header of the email. @type fromAddress: C{str} @param replyToAddress: the address to use in the C{Reply-To} header. @type replyToAddress: C{str} @param toAddress: the address to use in the C{To} header. @type toAddress: C{str} @param language: a 2-letter language code describing the target language that the email should be generated in. @type language: C{str} @return: a 2-tuple of C{str}s: (message ID, message text). The message ID is the value of the C{Message-ID} header, and the message text is the full MIME message, ready for transport over SMTP. """ details = self.getEventDetails(calendar, language=language) canceled = (calendar.propertyValue("METHOD") == "CANCEL") subjectFormat, labels = localizedLabels(language, canceled, inviteState) details.update(labels) details['subject'] = subjectFormat % {'summary' : details['summary']} plainText = self.renderPlainText(details, (orgCN, orgEmail), attendees, canceled) htmlText = self.renderHTML(details, (orgCN, orgEmail), attendees, canceled) msg = MIMEMultipart() msg["From"] = fromAddress msg["Subject"] = details['subject'] msg["Reply-To"] = replyToAddress msg["To"] = toAddress msg["Date"] = rfc822date() msgId = messageid() msg["Message-ID"] = msgId msgAlt = MIMEMultipart("alternative") msg.attach(msgAlt) # plain version msgPlain = MIMEText(plainText, "plain", "UTF-8") msgAlt.attach(msgPlain) # html version msgHtmlRelated = MIMEMultipart("related", type="text/html") msgAlt.attach(msgHtmlRelated) msgHtml = MIMEText(htmlText, "html", "UTF-8") msgHtmlRelated.attach(msgHtml) # the icalendar attachment # Make sure we always have the timezones used in the calendar data as iMIP requires VTIMEZONE # always be present (i.e., timezones-by-reference is not allowed in iMIP). calendarText = calendar.getTextWithTimezones(includeTimezones=True) self.log.debug("Mail gateway sending calendar body: %s" % (calendarText,)) msgIcal = MIMEText(calendarText, "calendar", "UTF-8") method = calendar.propertyValue("METHOD").lower() msgIcal.set_param("method", method) msgIcal.add_header("Content-ID", "<invitation.ics>") msgIcal.add_header("Content-Disposition", "inline;filename=invitation.ics") msg.attach(msgIcal) return msgId, msg.as_string()
if args.attachment_filename is not None: ctype, encoding = mimetypes.guess_type( args.attachment_filename) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) with open(args.attachment_filename, "rb") as attachment_file: inner = MIMEBase(maintype, subtype) inner.set_payload(attachment_file.read()) encoders.encode_base64(inner) inner.add_header('Content-Disposition', 'attachment', filename=args.attachment_filename) msg.attach(inner) server.sendmail(args.from_address, to_address, msg.as_string()) output_good("Email Sent to " + to_address) if args.slow_send: delay_send() output_info("Connecting to SMTP server at " + args.smtp_server + ":" + str(args.smtp_port)) server = smtplib.SMTP(args.smtp_server, args.smtp_port) except smtplib.SMTPException as e: output_error("Error: Could not send email") raise e
# 添加附件就是加上一个MIMEBase,从本地读取一个图片: with open('mail/pic.jpg', 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'jpg', filename='mail/pic.jpg') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='mail/pic.jpg') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的内容读进来: mime.set_payload(f.read()) # 用Base64编码: encoders.encode_base64(mime) # 添加到MIMEMultipart: msg.attach(mime) msg['From'] = _format_addr('Dad <%s>' % from_addr) msg['To'] = _format_addr('Son <%s>' % to_addr) msg['Subject'] = Header('Regards from Dad......', 'utf-8').encode() # SMTP协议默认端口 25 server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口 25 # server = smtplib.SMTP(smtp_server, 587) # 加密发送,qq端口 587 # server.starttls() # STARTTLS加密传输 server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
def main(args): import jinja2 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # Create the period name day = datetime.date.today() if args.period == Period.lastWeek: lastWeek = day - datetime.timedelta(days=7) periodName = lastWeek.strftime("%d/%m/%Y") periodTitle = "Weekly" elif args.period == Period.lastMonth: day = day.replace(day=1) lastMonth = day - datetime.timedelta(days=1) periodName = lastMonth.strftime("%m/%Y") periodTitle = "Monthly" elif args.period == Period.lastYear: day = day.replace(day=1) day = day.replace(month=1) lastYear = day - datetime.timedelta(days=1) periodName = lastYear.strftime("%Y") periodTitle = "Annual" else: periodName = "Beginning of time" periodTitle = "Full" user = None if args.user: user = args.user else: import getpass user = getpass.getuser() # The final recipient of the email. # When not specified, it will be the user recipient = None if args.recipient: recipient = args.recipient else: recipient = user # Format to use to send the email includeText = True includeHtml = True if args.mailFormat: includeText = "text" in args.mailFormat includeHtml = "html" in args.mailFormat reportBuilder = ReportBuilder(user, args.period) if reportBuilder.nbConnections() == 0: print("No connections for this period ({})".format(periodName)) sys.exit() # Update providers when they have not been updated reportBuilder.updateProviders() # Load statistics ispReport = reportBuilder.reportByProvider() countryReport = reportBuilder.reportByCountry() sourceReport = reportBuilder.reportBySource() statusReport = reportBuilder.reportByStatus() hourReport = reportBuilder.reportByHour() # Initialise the mime message message = MIMEMultipart("alternative") # Create the text template if includeText: logging.info( "Generating a text access report for user {}".format(user)) textTemplatePath = "/etc/homebox/access-report.d/monthly-report.text.j2" try: with open(textTemplatePath) as tmplFile: template = jinja2.Template(tmplFile.read()) text = template.render(ispReport=ispReport, countryReport=countryReport, sourceReport=sourceReport, statusReport=statusReport, hourReport=hourReport).replace( "_", " ") except Exception: raise TemplateError() # Attach the text part textPart = MIMEText(text, "plain") message.attach(textPart) logging.info("Generated text message") # Create the HTML template if includeHtml: logging.info( "Generating an HTML access report for user {}".format(user)) htmlTemplatePath = "/etc/homebox/access-report.d/monthly-report.html.j2" try: with open(htmlTemplatePath) as tmplFile: template = jinja2.Template(tmplFile.read()) html = template.render(ispReport=ispReport, countryReport=countryReport, sourceReport=sourceReport, statusReport=statusReport, hourReport=hourReport) except Exception: raise TemplateError() # Attach the message htmlPart = MIMEText(html, "html") message.attach(htmlPart) logging.info("Generated html message") # Add basic headers message["Subject"] = "{} access report for {} ({})".format( periodTitle, user, periodName) message["From"] = "postmaster" message["To"] = recipient # Create secure connection with server and send email server = smtplib.SMTP("localhost", 587) server.sendmail("postmaster", user, message.as_string())
from email.mime.multipart import MIMEMultipart smtp_server = "smtp.mail.bg" port = 25 # For starttls sender_email = "*****@*****.**" password = input("Type your password and press enter: ") msg = MIMEMultipart() msg["From"] = "*****@*****.**" msg["To"] = "[email protected],[email protected]" msg["Subject"] = "Test email to 2 addresses" # Create a secure SSL context context = ssl.create_default_context() # Try to log in to server and send email try: server = smtplib.SMTP(smtp_server,port) server.ehlo() # Can be omitted server.starttls(context=context) # Secure the connection server.ehlo() # Can be omitted server.login(sender_email, password) server.sendmail(msg["From"], msg["To"].split(","), msg.as_string()) # TODO: Send email here except Exception as e: # Print any error messages to stdout print(e) finally: print("Email has been send!") server.quit()
msg['subject'] = "Hello There Spartas!!" msg["From"] = from_list msg["To"] = to_list[0] plain_txt = "We are so glad to see you here!!" html_txt = """ <html> <head> <title>Testing</title> </head> <body> <p>Hey! <br>We are <b>testing</b> this email made by <a href=#>html tags</a>.</p> </body> </html>""" part_1 = MIMEText(plain_txt, 'plain') part_2 = MIMEText(html_txt, 'html') msg.attach(part_1) msg.attach(part_2) # print(msg.as_string()) print(email_con.sendmail(from_list, to_list, msg.as_string())) print(email_con.quit()) except smtplib.SMTPAuthenticationError: print("Error loading message") except smtplib.SMTPException: print("Error loading message")
def send_mail(receivers, resfile, img_list, appium_log): if not os.path.exists(resfile): return mail_host = "smtp.ym.163.com" mail_user = '******' mail_pass = '******' sender = '*****@*****.**' parsreceivers = [f'{name}@xinmoney.cn' for name in receivers] with open(resfile, 'rb') as f: resbody = f.read() message = MIMEMultipart() message['Subject'] = '自动化测试结果' message['From'] = sender message['To'] = ','.join(receivers) mail_body = resbody message.attach(MIMEText(mail_body, 'plain', 'utf-8')) logfile = MIMEText(open(resfile, 'rb').read(), 'base64', 'utf-8') logfile['Content-Type'] = 'application/octet-stream' logfile[ 'Content-Disposition'] = f'attachment; filename={os.path.basename(resfile)}' message.attach(logfile) # 将appiumlog发送到邮件中 for appiumlog in appium_log: appiumlogfile = MIMEText( open(appiumlog, 'rb').read(), 'base64', 'utf-8') appiumlogfile['Content-Type'] = 'application/octet-stream' appiumlogfile[ 'Content-Disposition'] = f'attachment; filename={os.path.basename(appiumlog)}' message.attach(appiumlogfile) # 将图片发送到邮件中 for img in img_list: part = MIMEApplication(open(img, 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(img)) message.attach(MIMEText(f'\n\n{img}:\n\n', 'text', 'utf-8')) message.attach(part) try: # smtpObj = smtplib.SMTP() # smtpObj.connect(mail_host,25) smtpobj = smtplib.SMTP_SSL(mail_host, 465) smtpobj.login(mail_user, mail_pass) smtpobj.sendmail(sender, parsreceivers, message.as_string()) smtpobj.quit() print('success') # 发送邮件成功后删除图片和autolog for img in img_list: os.remove(img) for appiumlog in appium_log: os.remove(appiumlog) logging.shutdown() os.remove(resfile) except smtplib.SMTPException as e: print('error:', e.args) print(e.with_traceback(e.__traceback__))
# Record the MIME type - part1 = MIMEText(html, 'html') msg.attach(part1) # Send the message via local SMTP server - mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login('*****@*****.**', 's/987456321/G') mail.sendmail(sender, recievers, msg.as_string()) mail.quit() # In[ ]: # In[ ]:
# Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(path, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(path, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(path, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=name) outer.attach(msg) with open(eml_file, 'w') as fp: fp.write(outer.as_string()) # ret = parse_msg.main(path) # eml_res[name] = ret cnt = cnt + 1 else: print(name, "dosya değil!") print('Toplam dosya sayisi: ', cnt)
# You might also need to chane this code # In my example the files have naming like certificate_01.pdf, certificate_02.pdf ... filename = FILE_PREFIX + \ str(record).zfill(ZERO_PADDING) + '.' + FILE_TYPE filepath = DOCS_FOLDER + filename sent_filename = SENT_FILE_PREFIX + \ str(record).zfill(ZERO_PADDING) + '.' + FILE_TYPE with open(filepath, "rb") as f: attach = MIMEApplication(f.read(), _subtype=FILE_TYPE) attach.add_header('Content-Disposition', 'attachment', filename=sent_filename) message.attach(attach) server.sendmail(SENDER, email, message.as_string()) print( f'{record} of {row_count}. Sent to {fullname}, {email}, with attached file {sent_filename}' ) # Need to delay every mail a bit to bypass mailtrap.io email per second rule. if DELAY_TIME > 0: sleep(DELAY_TIME) except Exception as e: print(f"Error occured for {record}") print(e) errors.append([record, fullname, email]) record += 1 # Stop execution if if record > MAX_RECORDS:
def method(self, **kwargs): # Don't bother with doc string, it will be over-written by createMethod. for name in kwargs.iterkeys(): if name not in parameters.argmap: raise TypeError('Got an unexpected keyword argument "%s"' % name) # Remove args that have a value of None. keys = kwargs.keys() for name in keys: if kwargs[name] is None: del kwargs[name] for name in parameters.required_params: if name not in kwargs: raise TypeError('Missing required parameter "%s"' % name) for name, regex in parameters.pattern_params.iteritems(): if name in kwargs: if isinstance(kwargs[name], basestring): pvalues = [kwargs[name]] else: pvalues = kwargs[name] for pvalue in pvalues: if re.match(regex, pvalue) is None: raise TypeError( 'Parameter "%s" value "%s" does not match the pattern "%s"' % (name, pvalue, regex)) for name, enums in parameters.enum_params.iteritems(): if name in kwargs: # We need to handle the case of a repeated enum # name differently, since we want to handle both # arg='value' and arg=['value1', 'value2'] if (name in parameters.repeated_params and not isinstance(kwargs[name], basestring)): values = kwargs[name] else: values = [kwargs[name]] for value in values: if value not in enums: raise TypeError( 'Parameter "%s" value "%s" is not an allowed value in "%s"' % (name, value, str(enums))) actual_query_params = {} actual_path_params = {} for key, value in kwargs.iteritems(): to_type = parameters.param_types.get(key, 'string') # For repeated parameters we cast each member of the list. if key in parameters.repeated_params and type(value) == type([]): cast_value = [_cast(x, to_type) for x in value] else: cast_value = _cast(value, to_type) if key in parameters.query_params: actual_query_params[parameters.argmap[key]] = cast_value if key in parameters.path_params: actual_path_params[parameters.argmap[key]] = cast_value body_value = kwargs.get('body', None) media_filename = kwargs.get('media_body', None) if self._developerKey: actual_query_params['key'] = self._developerKey model = self._model if methodName.endswith('_media'): model = MediaModel() elif 'response' not in methodDesc: model = RawModel() headers = {} headers, params, query, body = model.request(headers, actual_path_params, actual_query_params, body_value) expanded_url = uritemplate.expand(pathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) resumable = None multipart_boundary = '' if media_filename: # Ensure we end up with a valid MediaUpload object. if isinstance(media_filename, basestring): (media_mime_type, encoding) = mimetypes.guess_type(media_filename) if media_mime_type is None: raise UnknownFileType(media_filename) if not mimeparse.best_match([media_mime_type], ','.join(accept)): raise UnacceptableMimeTypeError(media_mime_type) media_upload = MediaFileUpload(media_filename, mimetype=media_mime_type) elif isinstance(media_filename, MediaUpload): media_upload = media_filename else: raise TypeError('media_filename must be str or MediaUpload.') # Check the maxSize if maxSize > 0 and media_upload.size() > maxSize: raise MediaUploadSizeError("Media larger than: %s" % maxSize) # Use the media path uri for media uploads expanded_url = uritemplate.expand(mediaPathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) if media_upload.resumable(): url = _add_query_parameter(url, 'uploadType', 'resumable') if media_upload.resumable(): # This is all we need to do for resumable, if the body exists it gets # sent in the first request, otherwise an empty body is sent. resumable = media_upload else: # A non-resumable upload if body is None: # This is a simple media upload headers['content-type'] = media_upload.mimetype() body = media_upload.getbytes(0, media_upload.size()) url = _add_query_parameter(url, 'uploadType', 'media') else: # This is a multipart/related upload. msgRoot = MIMEMultipart('related') # msgRoot should not write out it's own headers setattr(msgRoot, '_write_headers', lambda self: None) # attach the body as one part msg = MIMENonMultipart(*headers['content-type'].split('/')) msg.set_payload(body) msgRoot.attach(msg) # attach the media as the second part msg = MIMENonMultipart(*media_upload.mimetype().split('/')) msg['Content-Transfer-Encoding'] = 'binary' payload = media_upload.getbytes(0, media_upload.size()) msg.set_payload(payload) msgRoot.attach(msg) body = msgRoot.as_string() multipart_boundary = msgRoot.get_boundary() headers['content-type'] = ( 'multipart/related; ' 'boundary="%s"') % multipart_boundary url = _add_query_parameter(url, 'uploadType', 'multipart') logger.info('URL being requested: %s' % url) return self._requestBuilder(self._http, model.response, url, method=httpMethod, body=body, headers=headers, methodId=methodId, resumable=resumable)
class Email: def __init__(self, file_path=None): """初始化Email :param title: 邮件标题,必填。 :param message: 邮件正文,非必填。 :param path: 附件路径,可传入list(多附件)或str(单个附件),非必填。 :param server: smtp服务器,必填。 :param sender: 发件人,必填。 :param password: 发件人密码,必填。 :param receiver: 收件人,多收件人用“;”隔开,必填。 """ e = Config().get('Email') self.title = e.get('title') self.message = e.get('message') self.files = file_path self.msg = MIMEMultipart('related') self.server = e.get('server') self.sender = e.get('sender') self.receiver = e.get('receiver') self.password = e.get('password') def _attach_file(self, att_file): """将单个文件添加到附件列表中""" att = MIMEText(open('%s' % att_file, 'rb').read(), 'plain', 'utf-8') att["Content-Type"] = 'application/octet-stream' file_name = re.split(r'[\\|/]', att_file) att["Content-Disposition"] = 'attachment; filename="%s"' % file_name[-1] self.msg.attach(att) logger.info('attach file {}'.format(att_file)) def send(self): self.msg['Subject'] = self.title self.msg['From'] = self.sender self.msg['To'] = self.receiver # 邮件正文 if self.message: self.msg.attach(MIMEText(self.message)) # 添加附件,支持多个附件(传入list),或者单个附件(传入str) if self.files: if isinstance(self.files, list): for f in self.files: self._attach_file(f) elif isinstance(self.files, str): self._attach_file(self.files) # 连接服务器并发送 try: smtp_server = smtplib.SMTP_SSL(self.server,465) # 连接sever except (gaierror and error) as e: logger.exception('发送邮件失败,无法连接到SMTP服务器,检查网络以及SMTP服务器. %s', e) else: try: smtp_server.login(self.sender, self.password) # 登录 except smtplib.SMTPAuthenticationError as e: logger.exception('用户名密码验证失败!%s', e) else: smtp_server.sendmail(self.sender, self.receiver.split(';'), self.msg.as_string()) # 发送邮件 finally: smtp_server.quit() # 断开连接 logger.info('发送邮件"{0}"成功! 收件人:{1}。如果没有收到邮件,请检查垃圾箱,' '同时检查收件人地址是否正确'.format(self.title, self.receiver))
def sendmail(filename='c:/1.xlsx', receiver=['*****@*****.**'], ccreceiver=[], subject="擎天柱基金资产净值明细表", pwfile='./emailpanna.json'): mailinfo = file2dict(pwfile) sender = mailinfo['sender'] smtpserver = mailinfo['smtpserver'] username = mailinfo['username'] password = mailinfo['password'] # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = sender msg['To'] = ';'.join(receiver) msg['Cc'] = ';'.join(ccreceiver) # 定义发送时间(不定义的可能有的邮件客户端会不显示发送时间) msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z') # Create the body of the message (a plain-text and an HTML version). text = "你好,\n 附件是擎天柱基金资产净值明细表,请查收。" html = """\ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.python.org">link</a> you wanted. </p> </body> </html> """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) # msg.attach(part2) basename = os.path.basename(filename) ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' print("none.......") maintype, subtype = ctype.split('/', 1) fp = open(filename, 'rb') part3 = MIMEBase(maintype, subtype) part3.set_payload(fp.read()) encoders.encode_base64(part3) part3.add_header('Content-Disposition', 'attachment', filename=('gbk', '', basename)) msg.attach(part3) try: smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, receiver + ccreceiver, msg.as_string()) smtp.quit() except Exception as e: print(str(e))
Hi, How are you? Real Python has many great tutorials: www.realpython.com""" html = """\ <html> <body> <p>Hi,<br> How are you?<br> <a href="http://www.realpython.com">Real Python</a> has many great tutorials. </p> </body> </html> """ # Turn these into plain/html MIMEText objects part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach(part1) message.attach(part2) # Create secure connection with server and send email context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message.as_string())
def send(self, params, email, immediately=False): # checking for blacklisting try: obj = self.obj(EmailBlackList, email) except ObjectNotFoundException: pass else: # blacklisted return content = params["content"] subject = params["subject"] parts = params["parts"] params["description"] = self._("Email subject") subject = self.call("admin-email-sender.format", subject, params) if subject is None or not subject.strip(): return params["description"] = self._("Email content") content = self.call("admin-email-sender.format", content, params) if content is None or not content.strip(): return # converting data content = str2unicode(content) domain = self.app().canonical_domain protocol = self.app().protocol content += u'<br>--<br>{project_title} — <a href="{protocol}://{domain}/" target="_blank">{protocol}://{domain}</a><br>{your_name}<br>{unsubscribe}'.format( protocol=protocol, domain=domain, project_title=htmlescape(self.call("project.title")), your_name=self. _('Your name is {user_name} — <a href="{href}" target="_blank">remind password</a>' ).format( user_name=htmlescape(params.get("recipient_name")), href="{protocol}://{domain}/auth/remind?email={email}". format( protocol=protocol, domain=domain, email=urlencode(email), ), ), unsubscribe=self. _('To stop receiving letters press <a href="{href}" target="_blank">here</a>' ).format( href="{protocol}://{domain}/email/unsubscribe/{code}".format( protocol=protocol, domain=domain, code=self.call("email.unsubscribe-code", email), ), ), ) content = utf2str(content) # making MIME message multipart = MIMEMultipart("related") multipart["Subject"] = "%s%s" % (params["prefix"], Header(subject, "utf-8")) multipart["From"] = "%s <%s>" % (Header(params["name"], "utf-8"), params["email"]) multipart["To"] = "%s <%s>" % (Header(params["recipient_name"], "utf-8"), email) multipart["type"] = "text/html" try: multipart["X-Metagam-Project"] = self.app().tag except AttributeError: pass now = datetime.datetime.now() stamp = time.mktime(now.timetuple()) multipart["Date"] = formatdate(timeval=stamp, localtime=False, usegmt=True) # HTML part html_part = MIMEText(content, _subtype="html", _charset="utf-8") # Assembling multipart multipart.attach(html_part) for part in parts: multipart.attach(part) body = multipart.as_string() self.call("email.send", email, params["recipient_name"], subject, body, subtype="raw", immediately=immediately)