def copy_mime_root(msg, strip_content=True): """Make a copy of the non_payload root mime part of msg and change content type to multipart/alternativ. By default drop old Content- headers. """ msg_new = MIMEMultipart() # drop default keys for k in msg_new.keys(): del msg_new[k] # make copy of old header for k, v in msg.items(): if strip_content and k.startswith('Content-'): continue msg_new[k] = v if msg.get_unixfrom(): msg_new.set_unixfrom(msg.get_unixfrom()) if msg.preamble: msg_new.preamble = msg.preamble else: msg_new.preamble = "This is a multi-part message in MIME format...\n" if msg.epilogue: msg_new.epilogue = msg.epilogue # set msg_new type msg_new.set_type('multipart/alternative') return msg_new
def notifyUserFail(robot, arenanum, mailfrom, attPic=0, qualPic=25, attImg=1, delFiles=1, robotEMailAccount='*****@*****.**', PWrobotEMailAccount='examplePW'): gmail_user = robotEMailAccount gmail_password = PWrobotEMailAccount try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) except: print 'SMTP went wrong...' try: server.ehlo() except: print 'Handshake went wrong...' try: server.login(gmail_user, gmail_password) except: print 'Login went wrong...' if attImg == 1: msg = MIMEMultipart() for imgnum in range(len(arenanum)): curarenanum = str(arenanum[imgnum]) imgname = curarenanum + 'errImage.png' with open(imgname, 'rb') as fp: img = MIMEImage(fp.read()) msg.attach(img) if delFiles == 1: os.remove(imgname) fp.close() arenanum = str(arenanum) msg.preamble = 'Arena ' + arenanum + ' failed to unload.' msg['Subject'] = 'Failure: Arenas ' + arenanum + ' Withdraw' if attPic == 1: arenanum = str(arenanum) robot.light(True) time.sleep(0.2) robot.cam.start_live() robot.cam.snap_image() robot.cam.save_image(arenanum + 'errImage.png', 1, jpeq_quality=qualPic) robot.cam.stop_live() robot.dwell(50) robot.light(False) msg['Subject'] = 'Failure: Arena ' + arenanum + ' Withdraw' msg = MIMEMultipart() msg.preamble = 'Arena ' + arenanum + ' failed to unload.' fp = open(arenanum + 'errImage.png', 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) if delFiles == 1: os.remove(arenanum + 'errImage.png') if attPic == 0 and attImg == 0: arenanum = str(arenanum) msg['Subject'] = 'Failure: Arena ' + arenanum + ' Withdraw' msg['From'] = gmail_user msg['To'] = gmail_user server.sendmail(gmail_user, mailfrom, msg.as_string()) server.quit() return
def convert_tree(message, config, indent=0, wrap_alternative=True, charset=None): """Recursively convert a potentially-multipart tree. Returns a tuple of (the converted tree, whether any markdown was found) """ ct = message.get_content_type() cs = message.get_content_subtype() if charset is None: charset = get_charset_from_message_fragment(message) if not message.is_multipart(): # we're on a leaf converted = None disposition = message.get('Content-Disposition', 'inline') if disposition == 'inline' and ct in ('text/plain', 'text/markdown'): converted = convert_one(message, config, charset) if converted is not None: if wrap_alternative: new_tree = MIMEMultipart('alternative') _move_headers(message, new_tree) new_tree.attach(message) new_tree.attach(converted) return new_tree, True else: return converted, True return message, False else: if ct == 'multipart/signed': # if this is a multipart/signed message, then let's just # recurse into the non-signature part new_root = MIMEMultipart('alternative') if message.preamble: new_root.preamble = message.preamble _move_headers(message, new_root) converted = None for part in message.get_payload(): if part.get_content_type() != 'application/pgp-signature': converted, did_conversion = convert_tree(part, config, indent=indent + 1, wrap_alternative=False, charset=charset) if did_conversion: new_root.attach(converted) new_root.attach(message) return new_root, did_conversion else: did_conversion = False new_root = MIMEMultipart(cs, message.get_charset()) if message.preamble: new_root.preamble = message.preamble _move_headers(message, new_root) for part in message.get_payload(): part, did_this_conversion = convert_tree(part, config, indent=indent + 1, charset=charset) did_conversion |= did_this_conversion new_root.attach(part) return new_root, did_conversion
def send_report(): emailfrom = "" emailto = '' fileToSend = filename username = "" password = "" msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = emailto msg["Subject"] = "MainPage Test Report" msg.preamble = "MainPage Test Report" msg.preamble = "help I cannot send an attachment to save my life" ctype, encoding = mimetypes.guess_type(fileToSend) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(fileToSend) # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(fileToSend, "rb") attachment = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open(fileToSend, "rb") attachment = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: 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.mail.ru") server.starttls() server.login(username,password) server.sendmail(emailfrom, emailto, msg.as_string()) server.quit()
def pv_alert(EmailRecipients, LogName, TimeInterval, AlertType=0): CommaSpace = ', ' EmailSender = '*****@*****.**' # Create the container (outer) email message. msg = MIMEMultipart() # EmailSender == the sender's email address # EmailRecipients = the list of all recipients' email addresses msg['From'] = EmailSender msg['To'] = CommaSpace.join(EmailRecipients) if AlertType is 0: msg['Subject'] = 'TEST MODE: python alert: general error' msg.preamble = 'TEST MODE: python alert: general error' elif AlertType is 1: msg['Subject'] = 'TEST MODE: python alert: python says GE is too hot' msg.preamble = 'TEST MODE: python alert: python says GE is too hot' OrgTemp = [] BluTemp = [] with open(LogName, 'rb') as f: reader = csv.reader(f) for row in reader: if reader.line_num > 1: ### GE TEMPERATURES OrgTemp.append(float(row[84])) BluTemp.append(float(row[85])) x = numpy.linspace(1, len(OrgTemp), len(OrgTemp)) * TimeInterval plt.ion() fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, OrgTemp, 'v', x, BluTemp, '^') ax.set_xlabel('time (sec)') ax.set_ylabel('GE temperature (deg C)') plt.savefig('python_alert_image.png') plt.close() fp = open('python_alert_image.png', 'rb') img = MIMEImage(fp.read(), 'png') fp.close() msg.attach(img) # Send the email via our own SMTP server. s = smtplib.SMTP('localhost') s.sendmail(EmailSender, EmailRecipients, msg.as_string()) s.quit()
def test_send_mail(pict=None): try: host = '213.186.33.20' # ssl.ovh.net COMMASPACE = ', ' # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = 'Hello from the bird Feeder' mail_sender = '*****@*****.**' mail_recipients = ['*****@*****.**', '*****@*****.**', '*****@*****.**'] msg['From'] = mail_sender msg['To'] = COMMASPACE.join(mail_recipients) msg.preamble = 'Our family reunion' # text part of the message fp = open('text.txt', 'rb') # Create a text/plain message mt = MIMEText(fp.read()) fp.close() msg.attach(mt) # image part of the message fp = open(pict, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) # actuals sending server = smtplib.SMTP(host) server.login("*****@*****.**", "anna2004") server.sendmail(mail_sender, mail_recipients, msg.as_string()) server.quit() except SMTPAuthenticationError as e: print(e.smtp_error, e.smtp_code)
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 _prepare_message(self, addresses, subject, contents, use_cache, headers): """ Prepare a MIME message """ if self.is_closed: raise YagConnectionClosed('Login required again') if isinstance(contents, str): contents = [contents] has_included_images, content_objects = self._prepare_contents( contents, use_cache) msg = MIMEMultipart() if headers is not None: # Strangely, msg does not have an update method, so then manually. for k, v in headers.items(): msg[k] = v msg_alternative = MIMEMultipart('alternative') msg_related = MIMEMultipart('related') msg.attach(msg_alternative) self._add_subject(msg, subject) self._add_recipients_headers(msg, addresses) htmlstr = '' altstr = [] if has_included_images: msg.preamble = "This message is best displayed using a MIME capable email reader." if contents is not None: for content_object, content_string in zip(content_objects, contents): if content_object['main_type'] == 'image': # aliased image {'path' : 'alias'} if isinstance(content_string, dict) and len(content_string) == 1: for key in content_string: hashed_ref = str(abs(hash(key))) alias = content_string[key] # pylint: disable=undefined-loop-variable content_string = key else: alias = os.path.basename(content_string) hashed_ref = str(abs(hash(alias))) # if string is `inline`, inline, else, attach # pylint: disable=unidiomatic-typecheck if type(content_string) == inline: htmlstr += '<img src="cid:{}" title="{}"/>'.format( hashed_ref, alias) content_object['mime_object'].add_header( 'Content-ID', '<{}>'.format(hashed_ref)) altstr.append( '-- img {} should be here -- '.format(alias)) if content_object['encoding'] == 'base64': email.encoders.encode_base64(content_object['mime_object']) msg.attach(content_object['mime_object']) else: content_string = content_string.replace('\n', '<br>') htmlstr += '<div>{}</div>'.format(content_string) altstr.append(content_string) msg_related.attach(MIMEText(htmlstr, 'html', _charset='utf-8')) msg_alternative.attach(MIMEText('\n'.join(altstr), _charset='utf-8')) msg_alternative.attach(msg_related) return msg
def email_certi( filename, receiver ): username = "" password = "" sender = username + '@gmail.com' msg = MIMEMultipart() msg['Subject'] = 'NSS certificate' msg['From'] = username+'@gmail.com' msg['Reply-to'] = username + '@gmail.com' msg['To'] = receiver # That is what u see if dont have an email reader: msg.preamble = 'Multipart massage.\n' # Body part = MIMEText( "Hello,\n\nPlease find attached your NSS certificate.\n\nGreetings." ) msg.attach( part ) # Attachment part = MIMEApplication(open(filename,"rb").read()) part.add_header('Content-Disposition', 'attachment', filename = os.path.basename(filename)) msg.attach( part ) # Login server = smtplib.SMTP( 'smtp.gmail.com:587' ) server.starttls() server.login( username, password ) # Send the email server.sendmail( msg['From'], msg['To'], msg.as_string() )
def send_subscription_confirmation(self, to_addr, subject): """ Sends a HTML email subscription successful to the specified address :to_addr: The to address to be used when sending the message :subject: The subject for the message """ self.logger.debug('Trying to connect to server') self.setup() self.logger.debug('Connected to mail server successfully, sending message...') try: # Create message container - the correct MIME type is multipart/alternative here! message = MIMEMultipart('alternative') message['subject'] = subject message['To'] = to_addr message['From'] = self._mail_values['MAIL_FROM'] message.preamble = """ Your mail reader does not support the report format. Please visit us <a href="http://bloowatch.com">online</a>!""" html = render_template('subscription.html', user_email=to_addr) # print html # Record the MIME type text/html. html_body = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. message.attach(html_body) self.server.sendmail(self._mail_values['MAIL_FROM'], to_addr, message.as_string()) self.logger.info('Sent subscription mail correctly!') self.server.quit() except SMTPServerDisconnected: self.logger.info('Could not send mail, looks like server disconnected us!')
def _generatePGPMIME(self,mail, ciphertext): # intialize multipart email and set preamble multipart = MIMEMultipart("encrypted") multipart.preamble = "This is an OpenPGP/MIME encrypted message (RFC 4880 and 3156)" # first part is the Version Information del multipart['MIME-Version'] pgpencrypted = MIMEApplication("Version: 1","pgp-encrypted",email.encoders.encode_noop) pgpencrypted.add_header("Content-Description","PGP/MIME version identification") del pgpencrypted['MIME-Version'] # the second part contains the encrypted content octetstream = MIMEApplication(ciphertext,"octet-stream",email.encoders.encode_noop,name="encrypted.asc") octetstream.add_header("Content-Disposition","inline",filename='encrypted.asc'); octetstream.add_header("Content-Description","OpenPGP encrypted message") del octetstream['MIME-Version'] multipart.attach(pgpencrypted) multipart.attach(octetstream) # copy headers from original email for key in mail.keys(): multipart[key] = mail[key] multipart.set_param("protocol","application/pgp-encrypted"); del multipart['Content-Transfer-Encoding'] return multipart
def send_mail(subject, text, send_from="", dest_to=None, server="localhost", port=25, user="", passwd=""): """Send a email with a local or an external SMTP server. Arguments: (str) subject -- the mail's subject (str) text -- the message's text (str) send_from -- a sender's email address (default "") (list) dest_to -- a list of receivers' email addresses (default None) (str) server -- the smtp server (default "localhost") (int) port -- the smtp server port (default 25) (str) user -- the smtp server user (default "") (str) passwd --the smtp server password (default "") If "send_from" or "dest_to" are empty or None, then script user's mailbox is assumed instead. Useful for logging scripts """ local_email = "@".join([getpass.getuser(), socket.gethostname()]) send_from = send_from if send_from else local_email dest_to = dest_to if dest_to else [local_email] dest_to_addrs = COMMASPACE.join(dest_to) # receivers mails message = MIMEMultipart() message["Subject"] = subject message["From"] = send_from message["To"] = dest_to_addrs message["Date"] = formatdate(localtime=True) message.preamble = "You'll not see this in a MIME-aware mail reader.\n" message.attach(MIMEText(text)) # initialize the mail server smtp_server = smtplib.SMTP() # Connect to mail server try: smtp_server.connect(server, port) except socket.gaierror: print("mail error", "Wrong server, are you sure is correct?") except socket.error: print("mail error", "Server unavailable or connection refused") # Login in mail server if server != "localhost": try: smtp_server.login(user, passwd) except smtplib.SMTPAuthenticationError: print("mail error", "Authentication error") except smtplib.SMTPException: print("mail error", "No suitable authentication method") # Send mail try: smtp_server.sendmail(send_from, dest_to_addrs, message.as_string()) except smtplib.SMTPRecipientsRefused: print("mail error", "All recipients were refused." "Nobody got the mail.") except smtplib.SMTPSenderRefused: print("mail error", "The server didn’t accept the from_addr") except smtplib.SMTPDataError: print("mail error", "An unexpected error code, Data refused") # Disconnect from server smtp_server.quit()
def sendEmail(TO, FROM, SUBJECT, MESSAGE, ATTACH=False): ################################################################################ # Determine type of email if ATTACH != False: msg = MIMEMultipart() else: msg = MIMEText(MESSAGE) # this works for both types of emails msg['Subject'] = SUBJECT msg['From'] = FROM msg['To'] = TO if ATTACH != False: # That is what u see if dont have an email reader: msg.preamble = 'Multipart massage.\n' # This is the textual part: part = MIMEText(MESSAGE) msg.attach(part) # This is the binary part(The Attachment): part = MIMEApplication(open(ATTACH,"rb").read()) part.add_header('Content-Disposition', 'attachment', filename=ATTACH) msg.attach(part) s = smtplib.SMTP(SERVER) s.sendmail(FROM, [TO], msg.as_string()) s.quit()
def emailTumblr(gmail_user_name, gmail_pass_word, random_word ): # now send the email to Tumblr # email set up server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() #Next, log in to the server #print "user: "******"pass: "******"rb").read(), _subtype="jpeg") img.add_header('Content-Disposition', 'attachment; filename="newImageChanged.jpg"') msg.attach(img) server.sendmail(me, tumblr_email, msg.as_string()) server.quit()
def email_success_attachments(dirname, attachments): """ Email administrator a success message with need for manual attachments. Parameters: dirname: Name of unzipped ProQuest ETD directory """ # Set up multipart message msg = MIMEMultipart() msg['Subject'] = '%s requires manual intervention' % dirname msg['To'] = RESULT_EMAIL msg['From'] = "pi@localhost" msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' # Create and add body body = "%s/Output.xml is ready to be uploaded.\n" % dirname body += "Additionally the following files will need to be manually attached: \n" for att in attachments: body += os.path.basename(att) + "\n" part1 = MIMEText(body, 'plain') msg.attach(part1) # Send the email using SMTP s = smtplib.SMTP_SSL(SMTP_SERVER, 465) s.login(SMTP_USER, SMTP_PASSWORD) s.sendmail("pi@localhost", RESULT_EMAIL, msg.as_string()) s.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 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_mail(self, correlations, time, script): """Simple convenience function which sends an email \ from the configured sender to receivers. :param correlations: number representing the combined \ number of threats to be reported. :type correlations: :mod:`int` :param time: the time it took for the calling program \ to execute and finish successfully. :type time: :mod:`string` :param script: the script which was invoked such that a \ detailed job description can be provided to correlation notifications. :type time: :mod:`string` """ description = self.get_description(script) message = Template(""" <br><img src="cid:image1" width="200"><br> <p>You are receiving this email because you are subscribed to <b>Assurant's Threat Intelligence notification service</b>.</p> <p><b>$corr threat correlation(s) have been identified</b> whilst running one of our threat correlation scripts.</p> <p>Identified correlations relate to: <b>$desc</b>.</p> <p>To view correlation(s) please visit the Kibana dashboard.</p> <p>Time taken to identify correlations was <b>$dur seconds</b>.</p> <p><i>To unsubscribe from this service please contact $sender</i>.</p> """) fullMessage = message.substitute(corr=correlations, dur=time, sender=sender, desc=description) # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'Assurant Threatelligence Update' msgRoot['From'] = sender msgRoot['To'] = receivers msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('This is the alternative plain text message.') msgAlternative.attach(msgText) # We reference the image in the IMG SRC attribute by the ID we give it below #msgRoot = MIMEText() msgText = MIMEText(fullMessage, 'html') msgAlternative.attach(msgText) # This example assumes the image is in the current directory fp = open('assurant-logo.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) smtpObj = smtplib.SMTP('smtp.gmail.com', 587) smtpObj.ehlo() smtpObj.starttls() smtpObj.login(sender, '') smtpObj.sendmail(sender, receivers, msgRoot.as_string()) smtpObj.quit()
def _multipart(self): """The email has attachments""" msg = MIMEMultipart('related') if self.Html: outer = MIMEMultipart('alternative') part1 = MIMEText(self.Body, 'plain', self.charset) part1.add_header('Content-Disposition', 'inline') part2 = MIMEText(self.Html, 'html', self.charset) part2.add_header('Content-Disposition', 'inline') outer.attach(part1) outer.attach(part2) msg.attach(outer) else: msg.attach(MIMEText(self.Body, 'plain', self.charset)) self._set_info(msg) msg.preamble = self.Subject for filename, cid in self.attachments: self._add_attachment(msg, filename, cid) return msg.as_string()
def _email_data(self, file_list): """ Send a list of file by email @param file_list: list of files to send """ if len(file_list)==0: return import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart sender_email = str(self._content.from_email_edit.text()) recv_email = str(self._content.to_email_edit.text()) msg = MIMEMultipart() msg["Subject"] = "[Mantid] Reduced data" msg["From"] = sender_email msg["To"] = recv_email msg.preamble = "Reduced data" body = MIMEText("The attached reflectivity files were sent by MantidPlot.") msg.attach(body) for file_path in file_list: output_file = open(file_path, 'r') file_name = os.path.basename(file_path) att = MIMEText(output_file.read()) att.add_header('Content-Disposition', 'attachment', filename=file_name) output_file.close() msg.attach(att) s = smtplib.SMTP('localhost') s.sendmail(recv_email, recv_email, msg.as_string()) s.quit()
def send_mail(to_list, sub, path): ctype, encoding = mimetypes.guess_type(path) me = '"huaizong"<*****@*****.**>"' outer = MIMEMultipart() outer['From'] = me outer['To'] = ';'.join(to_list) outer['Subject'] = Header(sub, 'utf-8') outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(path) # Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) fp.close() else: fp = open(path, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) outer.attach(msg) body_text = MIMEText(sub, 'plain', 'utf-8') outer.attach(body_text) try: s = smtplib.SMTP() s.connect('127.0.0.1') s.set_debuglevel(1) s.sendmail(me, to_list, outer.as_string()) s.quit() return True except Exception, e: print str(e) return False
def sendEmail(): msg = MIMEMultipart() msg['Subject'] = LOG_SUBJ msg['From'] = LOG_FROM msg['To'] = LOG_MAIL msg.preamble = LOG_MSG # attach each file in LOG_TOSEND list for file in LOG_TOSEND: # attach text file if file[-4:] == '.txt': fp = open(file) attach = MIMEText(fp.read()) fp.close() # attach images elif file[-4:] == '.png': fp = open(file, 'rb') attach = MIMEImage(fp.read()) fp.close() attach.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(attach) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(LOG_MAIL, LOG_PASS) server.sendmail(LOG_FROM, LOG_MAIL, msg.as_string()) server.quit()
def sendemail(templatedir, filename, subject, sender, receiver, game, player, pdfpath): try: outer = MIMEMultipart() outer['Subject'] = subject outer['From'] = sender outer['To'] = receiver outer.preamble = '' 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') text = MIMEText( str(mailstream(templatedir, filename, game=game, player=player)), 'plain', 'utf-8') outer.attach(text) 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: pass
def send(self, _from, _to, _subject, _content, attfile=None): msgRoot = MIMEMultipart('related') msgRoot['Subject'] = Header(_subject, self.encoding); msgRoot['From'] = _from; msgRoot['To'] = _to ##.split(','); msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) if not attfile == None: # 构造MIMEBase对象做为文件附件内容并附加到根容器 contype = 'application/octet-stream' maintype, subtype = contype.split('/', 1) ## 读入文件内容并格式化 data = open(attfile, 'rb') file_msg = email.MIMEBase.MIMEBase(maintype, subtype) file_msg.set_payload(data.read()) data.close() email.Encoders.encode_base64(file_msg) ## 设置附件头 basename = os.path.basename(attfile) file_msg.add_header('Content-Disposition', 'attachment', filename=basename) msgAlternative.attach(file_msg) msgText = MIMEText(_content, self.type, self.encoding); msgAlternative.attach(msgText) self.smtp.sendmail(_from, _to.split(','), msgRoot.as_string())
def SendEmail(text, subject, to, attachment): try: htmltext = "<html>%s</html>" % text msg = MIMEMultipart() # me == the sender's email address # you == the recipient's email address msg['Subject'] = subject msg['From'] = '*****@*****.**' msg['To'] = ", ".join(to) msg.preamble = htmltext if os.path.isfile(attachment): fp = open(attachment, 'rb') att = MIMEBase("application","pdf") ## FOR UKNOWN FILETYPES USE: att = MIMEBase("application","octet-stream") att.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(att) att.add_header('Content-Disposition', 'attachment', filename=os.path.split(attachment)[1]) msg.attach(att) # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('mailserver.domain.net') s.sendmail(msg['From'], to, msg.as_string()) s.quit() except Exception as e: print e.args[0]
def pack(sender_addr, recipient_addrs, subject, text=None, attachments=[], sender_name=None, html=None): if sender_name is None: sender_name = sender_addr sender_name = Header(sender_name, ENCODING).encode() msg_root = MIMEMultipart('mixed') msg_root['date'] = formatdate() msg_root['From'] = formataddr((sender_name, sender_addr)) msg_root['To'] = COMMASPACE.join(recipient_addrs) msg_root['Subject'] = Header(subject, ENCODING) msg_root.preamble = 'This is a multi-part message in MIME format.' msg_related = MIMEMultipart('related') msg_root.attach(msg_related) msg_alternative = MIMEMultipart('alternative') msg_related.attach(msg_alternative) if text: msg_text = MIMEText(text, 'plain', ENCODING) msg_alternative.attach(msg_text) if html: msg_html = MIMEText(html, 'html', ENCODING) msg_alternative.attach(msg_html) for child in format_attachments(attachments): msg_related.attach(child) return msg_root
def main(): ### CHANGE THESE VALUES: to = '*****@*****.**' subject = 'Image from Pythonista' gmail_user = '******' gmail_pwd = 'YOUR_PASSWORD' #Load a sample image, modify as needed: image = Image.open('Test_Lenna') print 'Connecting...' smtpserver = smtplib.SMTP("smtp.gmail.com", 587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(gmail_user, gmail_pwd) print 'Preparing message...' outer = MIMEMultipart() outer['Subject'] = subject outer['To'] = to outer['From'] = gmail_user outer.preamble = 'You will not see this in a MIME-aware email reader.\n' attachment = get_attachment(image) outer.attach(attachment) composed = outer.as_string() print 'Sending...' smtpserver.sendmail(gmail_user, to, composed) smtpserver.close() print 'Done.'
def send_gmail(SUBJECT, BODY, TO, FROM, password): """With this function we send out our html email""" # Create message container - the correct MIME type is multipart/alternative here! MESSAGE = MIMEMultipart('alternative') MESSAGE['subject'] = SUBJECT MESSAGE['To'] = TO MESSAGE['From'] = FROM MESSAGE.preamble = """ Your mail reader does not support the report format. Please visit us <a href="http://www.mysite.com">online</a>!""" # Record the MIME type text/html. HTML_BODY = MIMEText(BODY, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. MESSAGE.attach(HTML_BODY) # The actual sending of the e-mail server = smtplib.SMTP('smtp.gmail.com:587') # Print debugging output when testing if __name__ == "__main__": server.set_debuglevel(1) # Credentials (if needed) for sending the mail server.starttls() server.login(FROM,password) server.sendmail(FROM, [TO], MESSAGE.as_string()) server.quit()
def notify_ar_retract(self, ar, newar): bika_setup = api.get_bika_setup() laboratory = bika_setup.laboratory lab_address = "<br/>".join(laboratory.getPrintAddress()) mime_msg = MIMEMultipart('related') mime_msg['Subject'] = t( _("Erroneus result publication from ${request_id}", mapping={"request_id": ar.getRequestID()})) mime_msg['From'] = formataddr((encode_header(laboratory.getName()), laboratory.getEmailAddress())) to = [] contact = ar.getContact() if contact: to.append( formataddr((encode_header(contact.Title()), contact.getEmailAddress()))) for cc in ar.getCCContact(): formatted = formataddr( (encode_header(cc.Title()), cc.getEmailAddress())) if formatted not in to: to.append(formatted) managers = self.context.portal_groups.getGroupMembers('LabManagers') for bcc in managers: user = self.portal.acl_users.getUser(bcc) if user: uemail = user.getProperty('email') ufull = user.getProperty('fullname') formatted = formataddr((encode_header(ufull), uemail)) if formatted not in to: to.append(formatted) mime_msg['To'] = ','.join(to) aranchor = "<a href='%s'>%s</a>" % (ar.absolute_url(), ar.getRequestID()) naranchor = "<a href='%s'>%s</a>" % (newar.absolute_url(), newar.getRequestID()) addremarks = ('addremarks' in self.request and ar.getRemarks()) and ( "<br/><br/>" + _("Additional remarks:") + "<br/>" + ar.getRemarks().split("===")[1].strip() + "<br/><br/>") or '' sub_d = dict(request_link=aranchor, new_request_link=naranchor, remarks=addremarks, lab_address=lab_address) body = Template( "Some errors have been detected in the results report " "published from the Analysis Request $request_link. The Analysis " "Request $new_request_link has been created automatically and the " "previous has been invalidated.<br/>The possible mistake " "has been picked up and is under investigation.<br/><br/>" "$remarks $lab_address").safe_substitute(sub_d) msg_txt = MIMEText(safe_unicode(body).encode('utf-8'), _subtype='html') mime_msg.preamble = 'This is a multi-part MIME message.' mime_msg.attach(msg_txt) try: host = getToolByName(self.context, 'MailHost') host.send(mime_msg.as_string(), immediate=True) except Exception as msg: message = _( 'Unable to send an email to alert lab ' 'client contacts that the Analysis Request has been ' 'retracted: ${error}', mapping={'error': safe_unicode(msg)}) self.context.plone_utils.addPortalMessage(message, 'warning')
def sendEmail(recipients, text_body, html_body=None, subject=settings.MAIL_DEFAULT_SUBJECT, sender=settings.MAIL_DEFAULT_SENDER, data=None, attachments=[]): """ Send an Email asynchronously to recipients :param recipients: list :param text_body: str :param html_body: str :param subject: str :param sender: str :param data: dict :param attachments: list :return: None """ try: if data is not None: text_body += "\r\n\n" for key, value in data.items(): text_body += "{}: {}\n".format(key, value) text_body += "\n" # print("Creating email") msg_root = MIMEMultipart('alternative') msg_root['From'] = sender msg_root['To'] = ", ".join(recipients) msg_root['Subject'] = subject msg_root.preamble = "|-------------------MULTIPART_BOUNDARY-------------------|\n" # print("Adding text body to email") msg_root.attach(MIMEText(text_body, 'plain')) if html_body is not None and html_body != "": # print("Adding html body to email") msg_root.attach(MIMEText(html_body, 'html')) if len(attachments) > 0: # print("Adding attachments to email") for file in attachments: with open(file, 'rb') as fp: msg_attachments = MIMEBase('application', "octet-stream") msg_attachments.set_payload(fp.read()) encoders.encode_base64(msg_attachments) msg_attachments.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file)) msg_root.attach(msg_attachments) # check environ vars if in debug mode if settings.DEBUG: settings.MAIL_USERNAME = os.getenv('MAIL_USERNAME', settings.MAIL_USERNAME) settings.MAIL_PASSWORD = os.getenv('MAIL_PASSWORD', settings.MAIL_PASSWORD) # need to decrypt password if isinstance(settings.MAIL_PASSWORD, bytes): mailpass = AES_CTR.decrypt(settings.MAIL_PASSWORD).decode('utf-8') else: mailpass = settings.MAIL_PASSWORD # print("sending email") with smtplib.SMTP(settings.MAIL_SERVER, settings.MAIL_PORT) as server: server.connect(settings.MAIL_SERVER, settings.MAIL_PORT) server.ehlo() if settings.MAIL_USE_TLS: server.starttls() server.ehlo() server.login(settings.MAIL_USERNAME, mailpass) msg_root_str = msg_root.as_string() server.sendmail(sender, recipients, msg_root_str) server.quit() except Exception as ex: debugException(ex)
#!/usr/bin/python # _*_ codingL UTF-8 _*_ from __future__ import print_function import smtplib from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart COMMASPACE = ', ' msg = MIMEMultipart() msg['Subject'] = 'Our family reunion' msg['From'] = me msg['to'] = COMMASPACE.join(family) msg.preamble = 'Our family reunion' for file in pngfiles: fp = open(file, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) s = smtplib.SMTP('localhost') s.sendmail('*****@*****.**', ['*****@*****.**', '*****@*****.**'], msg.as_string()) s.quit()
def perform(self, req, summary): if summary is None: return False config = self.env.config encoding = 'utf-8' subject = self.subject if not config.getbool('notification', 'smtp_enabled'): return False from_email = config['notification'].get('smtp_from') from_name = config['notification'].get('smtp_from_name') replyto_email = config['notification'].get('smtp_replyto') from_email = from_email or replyto_email if not from_email: return False # Authentication info (optional) user_name = config['notification'].get('smtp_user') password = config['notification'].get('smtp_password') # Thanks to the author of this recipe: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810 add_charset('utf-8', SHORTEST, None, None) projname = config.get('project', 'name') # Create the root message and fill in from, to, and subject headers msg_root = MIMEMultipart('alternative') msg_root['To'] = str(', ').join(self.emails) msg_root['X-Mailer'] = 'ClientsPlugin for Trac' msg_root['X-Trac-Version'] = __version__ msg_root['X-Trac-Project'] = projname msg_root['Precedence'] = 'bulk' msg_root['Auto-Submitted'] = 'auto-generated' msg_root['Subject'] = subject msg_root['From'] = '%s <%s>' % (from_name or projname, from_email) msg_root['Reply-To'] = replyto_email msg_root.preamble = 'This is a multi-part message in MIME format.' view = 'plain' arg = "'%s'" % view result = self.transform(summary, view=arg) msg_text = MIMEText(str(result), view, encoding) msg_root.attach(msg_text) msg_related = MIMEMultipart('related') msg_root.attach(msg_related) view = 'html' arg = "'%s'" % view result = self.transform(summary, view=arg) # file = open('/tmp/send-client-email.html', 'w') # file.write(str(result)) # file.close() msg_text = MIMEText(str(result), view, encoding) msg_related.attach(msg_text) # Handle image embedding... view = 'images' arg = "'%s'" % view result = self.transform(summary, view=arg) if result: images = result.getroot() if images is not None: for img in images: if 'img' != img.tag: continue if not img.get('id') or not img.get('src'): continue with open(img.get('src'), 'rb') as fp: if not fp: continue msg_img = MIMEImage(fp.read()) msg_img.add_header('Content-ID', '<%s>' % img.get('id')) msg_related.attach(msg_img) # Send the email import smtplib smtp = smtplib.SMTP() # smtp_server, smtp_port) if False and user_name: smtp.login(user_name, password) smtp.connect() smtp.sendmail(from_email, self.emails, msg_root.as_string()) smtp.quit() return True
def main(): module = AnsibleModule(argument_spec=dict( username=dict(default=None), password=dict(default=None, no_log=True), host=dict(default='localhost'), port=dict(default=25, type='int'), sender=dict(default='root', aliases=['from']), to=dict(default='root', aliases=['recipients']), cc=dict(default=None), bcc=dict(default=None), subject=dict(required=True, aliases=['msg']), body=dict(default=None), attach=dict(default=None), headers=dict(default=None), charset=dict(default='us-ascii'), subtype=dict(default='plain'), secure=dict(default='try', choices=['always', 'never', 'try', 'starttls'], type='str'), timeout=dict(default=20, type='int'))) username = module.params.get('username') password = module.params.get('password') host = module.params.get('host') port = module.params.get('port') sender = module.params.get('sender') recipients = module.params.get('to') copies = module.params.get('cc') blindcopies = module.params.get('bcc') subject = module.params.get('subject') body = module.params.get('body') attach_files = module.params.get('attach') headers = module.params.get('headers') charset = module.params.get('charset') subtype = module.params.get('subtype') secure = module.params.get('secure') timeout = module.params.get('timeout') sender_phrase, sender_addr = parseaddr(sender) secure_state = False code = 0 auth_flag = "" if not body: body = subject smtp = smtplib.SMTP(timeout=timeout) if secure in ('never', 'try', 'starttls'): try: code, smtpmessage = smtp.connect(host, port=port) except smtplib.SMTPException as e: if secure == 'try': try: smtp = smtplib.SMTP_SSL(timeout=timeout) code, smtpmessage = smtp.connect(host, port=port) secure_state = True except ssl.SSLError as e: module.fail_json( rc=1, msg='Unable to start an encrypted session to %s:%s: %s' % (host, port, to_native(e)), exception=traceback.format_exc()) else: module.fail_json(rc=1, msg='Unable to Connect to %s:%s: %s' % (host, port, to_native(e)), exception=traceback.format_exc()) if (secure == 'always'): try: smtp = smtplib.SMTP_SSL(timeout=timeout) code, smtpmessage = smtp.connect(host, port=port) secure_state = True except ssl.SSLError as e: module.fail_json( rc=1, msg='Unable to start an encrypted session to %s:%s: %s' % (host, port, to_native(e)), exception=traceback.format_exc()) if int(code) > 0: try: smtp.ehlo() except smtplib.SMTPException as e: module.fail_json(rc=1, msg='Helo failed for host %s:%s: %s' % (host, port, to_native(e)), exception=traceback.format_exc()) auth_flag = smtp.has_extn('AUTH') if secure in ('try', 'starttls'): if smtp.has_extn('STARTTLS'): try: smtp.starttls() smtp.ehlo() auth_flag = smtp.has_extn('AUTH') secure_state = True except smtplib.SMTPException as e: module.fail_json( rc=1, msg='Unable to start an encrypted session to %s:%s: %s' % (host, port, to_native(e)), exception=traceback.format_exc()) else: if secure == 'starttls': module.fail_json( rc=1, msg='StartTLS is not offered on server %s:%s' % (host, port)) if username and password: if auth_flag: try: smtp.login(username, password) except smtplib.SMTPAuthenticationError: module.fail_json( rc=1, msg= 'Authentication to %s:%s failed, please check your username and/or password' % (host, port)) except smtplib.SMTPException: module.fail_json( rc=1, msg='No Suitable authentication method was found on %s:%s' % (host, port)) else: module.fail_json(rc=1, msg="No Authentication on the server at %s:%s" % (host, port)) msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = formataddr((sender_phrase, sender_addr)) msg.preamble = "Multipart message" if headers is not None: for hdr in [x.strip() for x in headers.split('|')]: try: h_key, h_val = hdr.split('=') msg.add_header(h_key, h_val) except: pass if 'X-Mailer' not in msg: msg.add_header('X-Mailer', "Ansible") to_list = [] cc_list = [] addr_list = [] if recipients is not None: for addr in [x.strip() for x in recipients.split(',')]: to_list.append(formataddr(parseaddr(addr))) addr_list.append(parseaddr(addr)[1]) # address only, w/o phrase if copies is not None: for addr in [x.strip() for x in copies.split(',')]: cc_list.append(formataddr(parseaddr(addr))) addr_list.append(parseaddr(addr)[1]) # address only, w/o phrase if blindcopies is not None: for addr in [x.strip() for x in blindcopies.split(',')]: addr_list.append(parseaddr(addr)[1]) if len(to_list) > 0: msg['To'] = ", ".join(to_list) if len(cc_list) > 0: msg['Cc'] = ", ".join(cc_list) part = MIMEText(body + "\n\n", _subtype=subtype, _charset=charset) msg.attach(part) if attach_files is not None: for file in attach_files.split(): try: fp = open(file, 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload(fp.read()) fp.close() encoders.encode_base64(part) part.add_header('Content-disposition', 'attachment', filename=os.path.basename(file)) msg.attach(part) except Exception as e: module.fail_json( rc=1, msg="Failed to send mail: can't attach file %s: %s" % (file, to_native(e)), exception=traceback.format_exc()) composed = msg.as_string() try: smtp.sendmail(sender_addr, set(addr_list), composed) except Exception as e: module.fail_json(rc=1, msg='Failed to send mail to %s: %s' % (", ".join(addr_list), to_native(e)), exception=traceback.format_exc()) smtp.quit() if not secure_state and (username and password): module.exit_json( changed=False, msg='Username and Password was sent without encryption') else: module.exit_json(changed=False)
def send_email_smtp( # pylint: disable=invalid-name,too-many-arguments,too-many-locals to: str, subject: str, html_content: str, config: Dict[str, Any], files: Optional[List[str]] = None, data: Optional[Dict[str, str]] = None, images: Optional[Dict[str, bytes]] = None, dryrun: bool = False, cc: Optional[str] = None, bcc: Optional[str] = None, mime_subtype: str = "mixed", ) -> None: """ Send an email with html content, eg: send_email_smtp( '*****@*****.**', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True) """ smtp_mail_from = config["SMTP_MAIL_FROM"] smtp_mail_to = get_email_address_list(to) msg = MIMEMultipart(mime_subtype) msg["Subject"] = subject msg["From"] = smtp_mail_from msg["To"] = ", ".join(smtp_mail_to) msg.preamble = "This is a multi-part message in MIME format." recipients = smtp_mail_to if cc: smtp_mail_cc = get_email_address_list(cc) msg["CC"] = ", ".join(smtp_mail_cc) recipients = recipients + smtp_mail_cc if bcc: # don't add bcc in header smtp_mail_bcc = get_email_address_list(bcc) recipients = recipients + smtp_mail_bcc msg["Date"] = formatdate(localtime=True) mime_text = MIMEText(html_content, "html") msg.attach(mime_text) # Attach files by reading them from disk for fname in files or []: basename = os.path.basename(fname) with open(fname, "rb") as f: msg.attach( MIMEApplication( f.read(), Content_Disposition="attachment; filename='%s'" % basename, Name=basename, )) # Attach any files passed directly for name, body in (data or {}).items(): msg.attach( MIMEApplication(body, Content_Disposition="attachment; filename='%s'" % name, Name=name)) # Attach any inline images, which may be required for display in # HTML content (inline) for msgid, imgdata in (images or {}).items(): image = MIMEImage(imgdata) image.add_header("Content-ID", "<%s>" % msgid) image.add_header("Content-Disposition", "inline") msg.attach(image) send_mime_email(smtp_mail_from, recipients, msg, config, dryrun=dryrun)
def send_email(recipients, subject, text, attachments=None, message_callback=None, **kwargs): """ Sends an email from the recipients email account to a list of recipients with given subject and text. :param recipients: A list of emails :param subject: A subject string :param text: A formatting text of content :param attachments: any attachments to add :param message_callback: function to pass the message to once complete :return: True if message sent, otherwise False """ if not any(recipients): log.trace('send_email got no recipients. Skipping.') return False # extract kwarg options retries = kwargs.get('retries', 3) server_timeout = kwargs.get('server_timeout', 600) use_smtp_ssl = kwargs.pop('use_smtp_ssl', False) # credentials and server options send_user = kwargs.pop('send_user', None) or get_env('SMTP_USER') send_mail = kwargs.pop('send_mail', None) or get_env('SMTP_USER') send_pswd = kwargs.pop('send_pswd', None) or get_env('SMTP_PSWD') smtp_host = kwargs.pop('smtp_host', None) or get_env('SMTP_HOST') smtp_port = kwargs.pop('smtp_port', None) or get_env('SMTP_PORT') if not all([send_user, send_mail, send_pswd, smtp_host, smtp_port]): raise RuntimeError( 'Can not send mail without SMTP details (send_user, send_mail, send_pswd, smtp_host, smtp_port)' ) # construct message outer = MIMEMultipart() outer['Subject'] = subject outer['To'] = ', '.join(recipients) outer['From'] = send_mail outer.attach(MIMEText(text)) outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' outer_no_attachments = outer message = outer_no_attachments.as_string() # attach files if attachments: attachments = [attachments ] if not isinstance(attachments, list) else attachments for fname in attachments: if isinstance(fname, tuple): fname, aname = fname else: aname = os.path.split(fname)[1] ctype, encoding = mimetypes.guess_type(fname) try: if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(fname) # Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(fname, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(fname, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(fname, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=aname) outer.attach(msg) except Exception as exc: log.warning( 'Exception preparing attachment: file={} exc={}'.format( fname, exc.message), exc_info=True) else: message = outer.as_string() # Prepare actual message if message_callback and callable(message_callback): message_callback(message) log.info('Sending email: recipients={} subject={}'.format( recipients, subject)) while retries > 0: retries -= 1 try: if use_smtp_ssl: log.trace( 'send_email: connecting to SMTP_SSL server: timeout={}'. format(server_timeout)) server = smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=server_timeout) else: log.trace( 'send_email: connecting to SMTP server: timeout={}'.format( server_timeout)) server = smtplib.SMTP(smtp_host, smtp_port, timeout=server_timeout) except Exception as exc: log.error( 'Exception connecting to SMTP server: exc={} trace...'.format( exc), exc_info=True) continue try: log.trace('send_email: sending ehlo') server.ehlo() # may not be needed or supported log.trace('send_email: starting TLS') server.starttls() # may not be needed or supported log.trace('send_email: logging in') server.login(send_user, send_pswd) except Exception as exc: log.error( 'Exception handshaking to SMTP server: exc={} trace...'.format( exc), exc_info=True) continue else: log.trace('connection to SMTP server succeeded. Sending mail') try: try: server.sendmail(send_mail, recipients, message) except smtplib.SMTPSenderRefused as exc: if 'size limits' in exc.smtp_error: log.warning( 'Exception sending mail due to size limits - sending without attachments: {}' .format(exc.message), exc_info=True) # TODO: a flag/kwarg to enable/disable this message = outer_no_attachments.as_string() server.sendmail(send_mail, recipients, message) else: raise except Exception as exc: log.error('Exception sending email: {}'.format(exc.message), exc_info=True) if retries > 0: log.debug( 'retrying to send mail again: retries_remaining={}'. format(retries)) else: log.trace('mail sent successfully') return True finally: # server.quit() server.close() else: log.error('Failed to send mail after retries') return False
def send_email_smtp( to, subject, html_content, config, files=None, data=None, images=None, dryrun=False, cc=None, bcc=None, mime_subtype="mixed", ): """ Send an email with html content, eg: send_email_smtp( '*****@*****.**', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True) """ smtp_mail_from = config.get("SMTP_MAIL_FROM") to = get_email_address_list(to) msg = MIMEMultipart(mime_subtype) msg["Subject"] = subject msg["From"] = smtp_mail_from msg["To"] = ", ".join(to) msg.preamble = "This is a multi-part message in MIME format." recipients = to if cc: cc = get_email_address_list(cc) msg["CC"] = ", ".join(cc) recipients = recipients + cc if bcc: # don't add bcc in header bcc = get_email_address_list(bcc) recipients = recipients + bcc msg["Date"] = formatdate(localtime=True) mime_text = MIMEText(html_content, "html") msg.attach(mime_text) # Attach files by reading them from disk for fname in files or []: basename = os.path.basename(fname) with open(fname, "rb") as f: msg.attach( MIMEApplication( f.read(), Content_Disposition="attachment; filename='%s'" % basename, Name=basename, )) # Attach any files passed directly for name, body in (data or {}).items(): msg.attach( MIMEApplication(body, Content_Disposition="attachment; filename='%s'" % name, Name=name)) # Attach any inline images, which may be required for display in # HTML content (inline) for msgid, body in (images or {}).items(): image = MIMEImage(body) image.add_header("Content-ID", "<%s>" % msgid) image.add_header("Content-Disposition", "inline") msg.attach(image) send_MIME_email(smtp_mail_from, recipients, msg, config, dryrun=dryrun)
from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.text import MIMEText emailfrom = "*****@*****.**" emailto = "*****@*****.**" fileToSend = "/home/dalchemy/crontab.text" username = "******" password = "******" msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = emailto msg["Subject"] = "help I cannot send an attachment to save my life" msg.preamble = "help I cannot send an attachment to save my life" ctype, encoding = mimetypes.guess_type(fileToSend) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(fileToSend) # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() encoders.encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment", filename=fileToSend) msg.attach(attachment)
def publishFromHTML(self, aruid, results_html): # The AR can be published only and only if allowed uc = getToolByName(self.context, 'uid_catalog') ars = uc(UID=aruid) if not ars or len(ars) != 1: return [] ar = ars[0].getObject() wf = getToolByName(ar, 'portal_workflow') allowed_states = ['verified', 'published'] # Publish/Republish allowed? if wf.getInfoFor(ar, 'review_state') not in allowed_states: # Pre-publish allowed? if not ar.getAnalyses(review_state=allowed_states): return [] # HTML written to debug file # debug_mode = App.config.getConfiguration().debug_mode "Commented by Yasir" debug_mode = True #" Added by Yasir" if debug_mode: tmp_fn = tempfile.mktemp(suffix=".html") logger.debug("Writing HTML for %s to %s" % (ar.Title(), tmp_fn)) open(tmp_fn, "wb").write(results_html) # Create the pdf report (will always be attached to the AR) # we must supply the file ourself so that createPdf leaves it alone. # This version replaces 'attachment' links; probably not required, # so it's repeated below, without these localise_images. # cleanup, results_html_for_pdf = self.localise_images(results_html) # pdf_fn = tempfile.mktemp(suffix=".pdf") # pdf_report = createPdf(htmlreport=results_html_for_pdf, outfile=pdf_fn) # for fn in cleanup: # os.remove(fn) # Create the pdf report (will always be attached to the AR) # we must supply the file ourself so that createPdf leaves it alone. pdf_fn = tempfile.mktemp(suffix=".pdf") pdf_report = createPdf(htmlreport=results_html, outfile=pdf_fn) # PDF written to debug file if debug_mode: logger.debug("Writing PDF for %s to %s" % (ar.Title(), pdf_fn)) else: os.remove(pdf_fn) recipients = [] contact = ar.getContact() lab = ar.bika_setup.laboratory if pdf_report: if contact: recipients = [{ 'UID': contact.UID(), 'Username': to_utf8(contact.getUsername()), 'Fullname': to_utf8(contact.getFullname()), 'EmailAddress': to_utf8(contact.getEmailAddress()), 'PublicationModes': contact.getPublicationPreference() }] reportid = ar.generateUniqueId('ARReport') report = _createObjectByType("ARReport", ar, reportid) report.edit(AnalysisRequest=ar.UID(), Pdf=pdf_report, Html=results_html, Recipients=recipients) report.unmarkCreationFlag() renameAfterCreation(report) # Set status to prepublished/published/republished status = wf.getInfoFor(ar, 'review_state') transitions = {'verified': 'publish', 'published': 'republish'} transition = transitions.get(status, 'prepublish') try: wf.doActionFor(ar, transition) except WorkflowException: pass # compose and send email. # The managers of the departments for which the current AR has # at least one AS must receive always the pdf report by email. # https://github.com/bikalabs/Bika-LIMS/issues/1028 mime_msg = MIMEMultipart('related') mime_msg['Subject'] = self.get_mail_subject(ar)[0] mime_msg['From'] = formataddr( (encode_header(lab.getName()), lab.getEmailAddress())) mime_msg.preamble = 'This is a multi-part MIME message.' msg_txt = MIMEText(results_html, _subtype='html') mime_msg.attach(msg_txt) to = [] mngrs = ar.getResponsible() for mngrid in mngrs['ids']: name = mngrs['dict'][mngrid].get('name', '') email = mngrs['dict'][mngrid].get('email', '') if (email != ''): to.append(formataddr((encode_header(name), email))) if len(to) > 0: # Send the email to the managers mime_msg['To'] = ','.join(to) attachPdf(mime_msg, pdf_report, pdf_fn) try: host = getToolByName(ar, 'MailHost') host.send(mime_msg.as_string(), immediate=True) except SMTPServerDisconnected as msg: logger.warn("SMTPServerDisconnected: %s." % msg) except SMTPRecipientsRefused as msg: raise WorkflowException(str(msg)) # Send report to recipients recips = self.get_recipients(ar) for recip in recips: if 'email' not in recip.get('pubpref', []) \ or not recip.get('email', ''): continue title = encode_header(recip.get('title', '')) email = recip.get('email') formatted = formataddr((title, email)) # Create the new mime_msg object, cause the previous one # has the pdf already attached mime_msg = MIMEMultipart('related') mime_msg['Subject'] = self.get_mail_subject(ar)[0] mime_msg['From'] = formataddr( (encode_header(lab.getName()), lab.getEmailAddress())) mime_msg.preamble = 'This is a multi-part MIME message.' msg_txt = MIMEText(results_html, _subtype='html') mime_msg.attach(msg_txt) mime_msg['To'] = formatted # Attach the pdf to the email if requested if pdf_report and 'pdf' in recip.get('pubpref'): attachPdf(mime_msg, pdf_report, pdf_fn) # For now, I will simply ignore mail send under test. if hasattr(self.portal, 'robotframework'): continue msg_string = mime_msg.as_string() # content of outgoing email written to debug file if debug_mode: tmp_fn = tempfile.mktemp(suffix=".email") logger.debug("Writing MIME message for %s to %s" % (ar.Title(), tmp_fn)) open(tmp_fn, "wb").write(msg_string) try: host = getToolByName(ar, 'MailHost') host.send(msg_string, immediate=True) except SMTPServerDisconnected as msg: logger.warn("SMTPServerDisconnected: %s." % msg) except SMTPRecipientsRefused as msg: raise WorkflowException(str(msg)) ar.setDatePublished(DateTime()) return [ar]
#!/usr/bin/env python3 # Used https://docs.python.org/3.4/library/email-examples.html as an example from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders import smtplib import sys msg = MIMEMultipart() msg['Subject'] = 'Re: COOKIES!' msg['From'] = "*****@*****.**" msg['To'] = "*****@*****.**" msg.preamble = 'gingerbread cookie recipe' payload = """ import sys, imp, os def get_mod(modname): fd, path, desc = imp.find_module(modname, sys.path[::-1]) return imp.load_module("orig_" + modname, fd, path, desc) locals().update(vars(get_mod(__name__))) try: if not os.path.isfile("C:/Windows/Temp/have_run"): os.system('nssm install zGrabber "C:\\\\Users\\\\alabaster_snowball\\\\4445.exe"') os.system('nssm set zGrabber AppExit Default Restart') os.system('nssm start zGrabber') open("C:/Windows/Temp/have_run", 'a').close() except:
time_forecast = dico_weather[i]["dt_txt"] temperature = round(dico_weather[i]["main"]["temp"] - 273.15, 2) humidity = dico_weather[i]["main"]["humidity"] weather_description = dico_weather[i]["weather"][0]["description"] Berlin_weather_fc.append( "Weather on {} is: {}°C, {}% of humidity and {}.".format( time_forecast, temperature, humidity, weather_description)) dt = datetime.datetime.now() dt_email = dt.strftime('%A %d %B of %Y') msgRoot = MIMEMultipart('related') msgRoot['Subject'] = "Good morning! News of {}".format((dt_email)) msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = "This is the morning email" msgText = MIMEText( '{}<br><img src="cid:0"><br>{}<br><img src="cid:1"><br>{}<br>{}<br>{}Enjoy the day!' .format(message_chicken, message_xkcd, cu_weather_message, Berlin_weather_fc[0], Berlin_weather_fc[1]), 'html') #embed the image + text msgRoot.attach(msgText) if status_chicken == 1: with open(last_part_url_image, 'rb') as im: msgImage = MIMEImage(im.read()) msgImage.add_header('Content-ID', '<0>') msgRoot.attach(msgImage) if status_xkcd == 1:
from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders gmail_user = '******' gmail_password = '******' ''' OUTRA TENTATIVA ''' msg = MIMEMultipart() msg['Subject'] = 'Assunto' msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' msg.preamble = "reuniao de familia" part = MIMEBase("image", "octet-stream") part.set_payload(open('teste.jpg', 'rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="teste.jpg"') #============================ #sent_from = gmail_user #to = ['*****@*****.**'] #subject = 'OMG Super Important Message' #body = 'OK' #img_data = open('teste.jpg', 'rb').read() '''with open('teste.jpg','rb') as fp: img = MIMEImage(fp.read())'''
def process_payment_office_email(payment, contact): try: timeNow = datetime.now() profile = ProfileMetaProp.objects.get(pk=1) FROM = 'Grinberg & Segal <{}>'.format(profile.from_email) USER = profile.user_name PASSWORD = profile.password PORT = profile.smtp_port SERVER = profile.smtp_server TO = contact.email email_cc_one = profile.to_email email_cc_two = profile.to_email_secondary email_cc_three = profile.to_email_third log = Logger(log='We are sending email to {}'.format(payment)) log.save() SUBJECT = 'Your payment has been processed' try: path = "templates/payment_message.html" f = codecs.open(path, 'r') m = f.read() mess = m mess = string.replace(m, '[fullname]', str(payment.fullname)) mess = string.replace(mess, '[greeting]', 'Dear') mess = string.replace( mess, '[greeting_statement]', 'You just made an online payment for Grinberg and Segal Family Law Division.' ) line1 = "<p>Please give us 1 to 3 busintess days to follow up.</p>" line2 = "<p>Truly Yours,<br/>" line3 = "Grinberg and Segal Family Law Division</p>" mess = string.replace(mess, '[wait_statement]', "{}{}{}".format(line1, line2, line3)) mess = string.replace(mess, '[greeting_global_link]', 'Gringerg and Segal Family Law Division') mess = string.replace(mess, '[global_link]', 'https://divorcesus.com') mess = string.replace(mess, '[greeting_locale]', 'New York, NY, USA') mess = string.replace(mess, '[invoice]', payment.payment.invoice) mess = string.replace(mess, '[address1]', str(payment.address1)) mess = string.replace(mess, '[address2]', str(payment.address2)) mess = string.replace(mess, '[city]', str(payment.city)) mess = string.replace(mess, '[state]', str(payment.state)) mess = string.replace(mess, '[zip]', str(payment.zipcode)) mess = string.replace(mess, '[phone]', str(payment.phone)) mess = string.replace(mess, '[email]', str(payment.email)) mess = string.replace(mess, '[package_type]', str(payment.package_type)) mess = string.replace(mess, '[package_price]', str(payment.package_price)) # mess = string.replace(mess,'[link]',link) except Exception as R: log = Logger(log="WE FAILED LOUDLY " + str(R)) log.save() message = mess log = Logger(log="WE are about to send ... ") log.save() MESSAGE = MIMEMultipart('alternative') MESSAGE['subject'] = SUBJECT MESSAGE['To'] = TO MESSAGE['Bcc'] = '{},{},{}'.format(email_cc_one, email_cc_two, email_cc_three) MESSAGE['From'] = FROM MESSAGE.preamble = """ Your mail reader does not support the report format. Please visit us <a href="http://www.mysite.com">online</a>!""" # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. HTML_BODY = MIMEText(message, 'html', 'utf-8') MESSAGE.attach(HTML_BODY) msg = MESSAGE.as_string() server = smtplib.SMTP(SERVER + ':' + PORT) server.ehlo() server.starttls() server.login(USER, PASSWORD) server.sendmail(FROM, TO, msg) server.quit() log = Logger(log="WE HAVE SENT EMAILS ") log.save() except SMTPRecipientsRefused: pass except ObjectDoesNotExist: pass except Exception, R: log = Logger(log="ANOTHER FAILURE HERE: " + str(R)) log.save()
"http://morning-ocean-4669.herokuapp.com/report/", 'method': 'GET' # The method used to call the url } response = p.send_message(params) print(response) uuid = str(response[1]['message_uuid'][0]) params1 = {'message_uuid': uuid} response1 = p.get_message(params1) ################################### Email service ######################### msg = MIMEMultipart() msg["From"] = emailfrom #msg["To"] = emailto msg["To"] = ", ".join(recepients) msg["Subject"] = "Promethean Data Loggers" msg.preamble = "Promethean Data Loggers" ctype, encoding = mimetypes.guess_type(fileToSend) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(fileToSend) # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(fileToSend, "rb") attachment = MIMEImage(fp.read(), _subtype=subtype)
def send_confirmation(user, hash): smtp_host = current_app.config['SMTP_HOST'] smtp_port = current_app.config['SMTP_PORT'] mail_localhost = current_app.config['MAIL_LOCALHOST'] ssl_key_file = current_app.config['SSL_KEY_FILE'] ssl_cert_file = current_app.config['SSL_CERT_FILE'] mail_from = current_app.config['MAIL_FROM'] smtp_username = current_app.config.get('SMTP_USERNAME', mail_from) smtp_password = current_app.config['SMTP_PASSWORD'] msg = MIMEMultipart('related') msg['Subject'] = "[Alerta] Please verify your email '%s'" % user.email msg['From'] = mail_from msg['To'] = user.email msg.preamble = "[Alerta] Please verify your email '%s'" % user.email text = 'Hello {name}!\n\n' \ 'Please verify your email address is {email} by clicking on the link below:\n\n' \ '{url}\n\n' \ 'You\'re receiving this email because you recently created a new Alerta account.' \ ' If this wasn\'t you, please ignore this email.'.format( name=user.name, email=user.email, url=absolute_url('/auth/confirm/' + hash) ) msg_text = MIMEText(text, 'plain', 'utf-8') msg.attach(msg_text) try: if current_app.config['SMTP_USE_SSL']: mx = smtplib.SMTP_SSL(smtp_host, smtp_port, local_hostname=mail_localhost, keyfile=ssl_key_file, certfile=ssl_cert_file) else: mx = smtplib.SMTP(smtp_host, smtp_port, local_hostname=mail_localhost) if current_app.config['DEBUG']: mx.set_debuglevel(True) mx.ehlo() if current_app.config['SMTP_STARTTLS']: mx.starttls() if smtp_password: mx.login(smtp_username, smtp_password) mx.sendmail(mail_from, [user.email], msg.as_string()) mx.close() except smtplib.SMTPException as e: logging.error('Failed to send email : %s', str(e)) except (socket.error, socket.herror, socket.gaierror) as e: logging.error('Mail server connection error: %s', str(e)) return except Exception as e: logging.error('Unhandled exception: %s', str(e))
#saving to excel file df.to_excel('NAME.xlsx', sheet_name='SHEET_NAME', index=False, header=False) print('Saved to excel file.') #sending email emailfrom = "YOUR_EMAIL" emailto = "RECEIPIENTS_HERE" fileToSend = "SHEET_NAME.xlsx" username = "******" password = "******" msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = ",".join(emailto) msg["Subject"] = "SUBJECT" msg.preamble = "BODY_MESSAGE" ctype, encoding = mimetypes.guess_type(fileToSend) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(fileToSend) # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(fileToSend, "rb") attachment = MIMEImage(fp.read(), _subtype=subtype)
from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from smtplib import SMTP import smtplib import sys recipients = ['*****@*****.**','*****@*****.**'] emaillist = [elem.strip().split(',') for elem in recipients] msg = MIMEMultipart() msg['Subject'] = str(sys.argv[1]) msg['From'] = '*****@*****.**' msg['Reply-to'] = '*****@*****.**' msg.preamble = 'Multipart massage.\n' part = MIMEText("Hi, please find the attached file") msg.attach(part) ############# This following function is used for the attachment file part = MIMEApplication(open(str(sys.argv[2]),"rb").read()) part.add_header('Content-Disposition', 'attachment', filename=str(sys.argv[2])) msg.attach(part) server = smtplib.SMTP("smtp.gmail.com:587") server.ehlo() server.starttls() server.login("*****@*****.**", "Thichca@987654")
def send_raw(self, job, message, config): config = dict(self.middleware.call_sync('mail.config'), **config) if config['fromname']: from_addr = Header(config['fromname'], 'utf-8') try: config['fromemail'].encode('ascii') except UnicodeEncodeError: from_addr.append(f'<{config["fromemail"]}>', 'utf-8') else: from_addr.append(f'<{config["fromemail"]}>', 'ascii') else: try: config['fromemail'].encode('ascii') except UnicodeEncodeError: from_addr = Header(config['fromemail'], 'utf-8') else: from_addr = Header(config['fromemail'], 'ascii') interval = message.get('interval') if interval is None: interval = timedelta() else: interval = timedelta(seconds=interval) sw_name = self.middleware.call_sync('system.info')['version'].split('-', 1)[0] channel = message.get('channel') if not channel: channel = sw_name.lower() if interval > timedelta(): channelfile = '/tmp/.msg.%s' % (channel) last_update = datetime.now() - interval try: last_update = datetime.fromtimestamp(os.stat(channelfile).st_mtime) except OSError: pass timediff = datetime.now() - last_update if (timediff >= interval) or (timediff < timedelta()): # Make sure mtime is modified # We could use os.utime but this is simpler! with open(channelfile, 'w') as f: f.write('!') else: raise CallError('This message was already sent in the given interval') verrors = self.__password_verify(config['pass'], 'mail-config.pass') if verrors: raise verrors to = message.get('to') if not to: to = [ self.middleware.call_sync( 'user.query', [('username', '=', 'root')], {'get': True} )['email'] ] if not to[0]: raise CallError('Email address for root is not configured') if message.get('attachments'): job.check_pipe("input") def read_json(): f = job.pipes.input.r data = b'' i = 0 while True: read = f.read(1048576) # 1MiB if read == b'': break data += read i += 1 if i > 50: raise ValueError('Attachments bigger than 50MB not allowed yet') if data == b'': return None return json.loads(data) attachments = read_json() else: attachments = None if 'html' in message or attachments: msg = MIMEMultipart() msg.preamble = message['text'] if 'html' in message: msg2 = MIMEMultipart('alternative') msg2.attach(MIMEText(message['text'], 'plain', _charset='utf-8')) msg2.attach(MIMEText(message['html'], 'html', _charset='utf-8')) msg.attach(msg2) if attachments: for attachment in attachments: m = Message() m.set_payload(attachment['content']) for header in attachment.get('headers'): m.add_header(header['name'], header['value'], **(header.get('params') or {})) msg.attach(m) else: msg = MIMEText(message['text'], _charset='utf-8') msg['Subject'] = message['subject'] msg['From'] = from_addr msg['To'] = ', '.join(to) if message.get('cc'): msg['Cc'] = ', '.join(message.get('cc')) msg['Date'] = formatdate() local_hostname = socket.gethostname() msg['Message-ID'] = "<%s-%s.%s@%s>" % (sw_name.lower(), datetime.utcnow().strftime("%Y%m%d.%H%M%S.%f"), base64.urlsafe_b64encode(os.urandom(3)), local_hostname) extra_headers = message.get('extra_headers') or {} for key, val in list(extra_headers.items()): if key in msg: msg.replace_header(key, val) else: msg[key] = val syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL) try: server = self._get_smtp_server(config, message['timeout'], local_hostname=local_hostname) # NOTE: Don't do this. # # If smtplib.SMTP* tells you to run connect() first, it's because the # mailserver it tried connecting to via the outgoing server argument # was unreachable and it tried to connect to 'localhost' and barfed. # This is because FreeNAS doesn't run a full MTA. # else: # server.connect() headers = '\n'.join([f'{k}: {v}' for k, v in msg._headers]) syslog.syslog(f"sending mail to {', '.join(to)}\n{headers}") server.sendmail(from_addr.encode(), to, msg.as_string()) server.quit() except Exception as e: # Don't spam syslog with these messages. They should only end up in the # test-email pane. # We are only interested in ValueError, not subclasses. if e.__class__ is ValueError: raise CallError(str(e)) syslog.syslog(f'Failed to send email to {", ".join(to)}: {str(e)}') if isinstance(e, smtplib.SMTPAuthenticationError): raise CallError(f'Authentication error ({e.smtp_code}): {e.smtp_error}', errno.EAUTH) self.logger.warn('Failed to send email: %s', str(e), exc_info=True) if message['queue']: with MailQueue() as mq: mq.append(msg) raise CallError(f'Failed to send email: {e}') return True
def send_mail( subject=None, text=None, interval=None, channel=None, to=None, extra_headers=None, attachments=None, timeout=300, queue=True, ): from freenasUI.account.models import bsdUsers from freenasUI.system.models import Email syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL) if interval is None: interval = timedelta() if not channel: channel = get_sw_name().lower() if interval > timedelta(): channelfile = '/tmp/.msg.%s' % (channel) last_update = datetime.now() - interval try: last_update = datetime.fromtimestamp(os.stat(channelfile).st_mtime) except OSError: pass timediff = datetime.now() - last_update if (timediff >= interval) or (timediff < timedelta()): # Make sure mtime is modified # We could use os.utime but this is simpler! with open(channelfile, 'w') as f: f.write('!') else: return True, 'This message was already sent in the given interval' error = False errmsg = '' em = Email.objects.all().order_by('-id')[0] if not to: to = [bsdUsers.objects.get(bsdusr_username='******').bsdusr_email] if not to[0]: return True, 'Email address for root is not configured' if attachments: msg = MIMEMultipart() msg.preamble = text list(map(lambda attachment: msg.attach(attachment), attachments)) else: msg = MIMEText(text, _charset='utf-8') if subject: msg['Subject'] = subject msg['From'] = em.em_fromemail msg['To'] = ', '.join(to) msg['Date'] = formatdate() local_hostname = _get_local_hostname() msg['Message-ID'] = "<%s-%s.%s@%s>" % ( get_sw_name().lower(), datetime.utcnow().strftime("%Y%m%d.%H%M%S.%f"), base64.urlsafe_b64encode(os.urandom(3)), local_hostname) if not extra_headers: extra_headers = {} for key, val in list(extra_headers.items()): if key in msg: msg.replace_header(key, val) else: msg[key] = val try: server = _get_smtp_server(timeout, local_hostname=local_hostname) # NOTE: Don't do this. # # If smtplib.SMTP* tells you to run connect() first, it's because the # mailserver it tried connecting to via the outgoing server argument # was unreachable and it tried to connect to 'localhost' and barfed. # This is because FreeNAS doesn't run a full MTA. # else: # server.connect() syslog.syslog("sending mail to " + ','.join(to) + msg.as_string()[0:140]) server.sendmail(em.em_fromemail, to, msg.as_string()) server.quit() except ValueError as ve: # Don't spam syslog with these messages. They should only end up in the # test-email pane. errmsg = str(ve) error = True except Exception as e: errmsg = str(e) log.warn('Failed to send email: %s', errmsg, exc_info=True) error = True if queue: with MailQueue() as mq: mq.append(msg) except smtplib.SMTPAuthenticationError as e: errmsg = "%d %s" % (e.smtp_code, e.smtp_error) error = True except: errmsg = "Unexpected error." error = True return error, errmsg
def sendEmail(fileToSend): import smtplib import mimetypes from email.mime.multipart import MIMEMultipart from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.text import MIMEText fileToSend = csvFilePath(fileToSend) emailfrom = "Endorse team" emailto = "*****@*****.**" fileToSend = fileToSend username = "******" password = "******" msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = emailto msg["Subject"] = "ENDORSE | " + fileToSend msg.preamble = "Streamer list" #newMarketers, oldMarketers = newSponsors(fileToSend) #text = defineText(newMarketers, oldMarketers) ctype, encoding = mimetypes.guess_type(fileToSend) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(fileToSend) # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(fileToSend, "rb") attachment = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open(fileToSend, "rb") attachment = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: 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) #msg.attach(MIMEText(text)) server = smtplib.SMTP("smtp.gmail.com:587") server.starttls() server.login(username, password) server.sendmail(emailfrom, emailto, msg.as_string()) server.quit() return
async def send_email(cemail, v_code, author): consoleout = client.get_channel(698216599970381895) strFrom = 'The Atrium <*****@*****.**>' strTo = cemail print('starting msg creating') # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'The Atrium Verification Code' msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('This is the alternative plain text message.') msgAlternative.attach(msgText) # We reference the image in the IMG SRC attribute by the ID we give it below msgText = MIMEText(f''' <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head> <title> </title> <!--[if !mso]><!-- --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!--<![endif]--> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> #outlook a {{ padding:0; }} .ReadMsgBody {{ width:100%; }} .ExternalClass {{ width:100%; }} .ExternalClass * {{ line-height:100%; }} body {{ margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }} table, td {{ border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }} img {{ border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }} p {{ display:block;margin:13px 0; }} </style> <!--[if !mso]><!--> <style type="text/css"> @media only screen and (max-width:480px) {{ @-ms-viewport {{ width:320px; }} @viewport {{ width:320px; }} }} </style> <!--<![endif]--> <!--[if mso]> <xml> <o:OfficeDocumentSettings> <o:AllowPNG/> <o:PixelsPerInch>96</o:PixelsPerInch> </o:OfficeDocumentSettings> </xml> <![endif]--> <!--[if lte mso 11]> <style type="text/css"> .outlook-group-fix {{ width:100% !important; }} </style> <![endif]--> <!--[if !mso]><!--> <link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Cabin:400,700" rel="stylesheet" type="text/css"> <style type="text/css"> @import url(https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700); @import url(https://fonts.googleapis.com/css?family=Cabin:400,700); </style> <!--<![endif]--> <style type="text/css"> @media only screen and (min-width:480px) {{ .mj-column-per-100 {{ width:100% !important; max-width: 100%; }} }} </style> <style type="text/css"> @media only screen and (max-width:480px) {{ table.full-width-mobile {{ width: 100% !important; }} td.full-width-mobile {{ width: auto !important; }} }} </style> <style type="text/css">.hide_on_mobile {{ display: none !important;}} @media only screen and (min-width: 480px) {{ .hide_on_mobile {{ display: block !important;}} }} .hide_section_on_mobile {{ display: none !important;}} @media only screen and (min-width: 480px) {{ .hide_section_on_mobile {{ display: table !important;}} }} .hide_on_desktop {{ display: block !important;}} @media only screen and (min-width: 480px) {{ .hide_on_desktop {{ display: none !important;}} }} .hide_section_on_desktop {{ display: table !important;}} @media only screen and (min-width: 480px) {{ .hide_section_on_desktop {{ display: none !important;}} }} [owa] .mj-column-per-100 {{ width: 100%!important; }} [owa] .mj-column-per-50 {{ width: 50%!important; }} [owa] .mj-column-per-33 {{ width: 33.333333333333336%!important; }} p {{ margin: 0px; }} @media only print and (min-width:480px) {{ .mj-column-per-100 {{ width:100%!important; }} .mj-column-per-40 {{ width:40%!important; }} .mj-column-per-60 {{ width:60%!important; }} .mj-column-per-50 {{ width: 50%!important; }} mj-column-per-33 {{ width: 33.333333333333336%!important; }} }}</style> </head> <body style="background-color:#FFFFFF;"> <div style="background-color:#FFFFFF;"> <!--[if mso | IE]> <table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" > <tr> <td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"> <![endif]--> <div style="Margin:0px auto;max-width:600px;"> <table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%;"> <tbody> <tr> <td style="direction:ltr;font-size:0px;padding:9px 0px 9px 0px;text-align:center;vertical-align:top;"> <!--[if mso | IE]> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="" style="vertical-align:top;width:600px;" > <![endif]--> <div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"> <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:top;" width="100%"> <tbody><tr> <td align="center" style="font-size:0px;padding:0px 0px 0px 0px;word-break:break-word;"> <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:collapse;border-spacing:0px;"> <tbody> <tr> <td style="width:102px;"> <img height="auto" src="cid:image1" style="border:0;display:block;outline:none;text-decoration:none;height:auto;width:100%;font-size:13px;" width="102"> </td> </tr> </tbody> </table> </td> </tr> <tr> <td align="left" style="font-size:0px;padding:15px 15px 15px 15px;word-break:break-word;"> <div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:11px;line-height:1.5;text-align:left;color:#000000;"> <p style="text-align: center;"><span style="font-size: 13px;">Thanks for verifying, {author} . Welcome to The Atrium. Copy and paste this command in the #welcome-verify channel: <b>.code {v_code}</b>.</span></p> </div> </td> </tr> <tr> <td align="left" style="font-size:0px;padding:15px 15px 15px 15px;word-break:break-word;"> <div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:11px;line-height:1.5;text-align:left;color:#000000;"> <p style="text-align: center;"><span style="font-family: terminal, monaco, monospace; font-size: 48px;">.code {v_code}</span></p> </div> </td> </tr> </tbody></table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </td> </tr> </tbody> </table> </div> <!--[if mso | IE]> </td> </tr> </table> <![endif]--> </div> </body></html> ''', 'html') msgAlternative.attach(msgText) print('starting logo open process') # This example assumes the image is in the current directory fp: object = open('logoHR.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) # Send the email (this example assumes SMTP authentication is required) print("starting STMP") smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.connect('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls() smtp.ehlo() print("connected to STMP") smtp.login('*****@*****.**', 'logobot!!') print("logged in") try: smtp.sendmail(strFrom, strTo, msgRoot.as_string()) except: print("sendmail failed") print("email sent!") smtp.quit()
def insert_extracts(self, user, payload): """Insert multiple extracts into the database, as a single request :param user: :param payload: :return: """ conn = g._db db_name = self._config.get("MySql", "db") env = self._config.get("api", "env") cor_admin = user.get("digs") # self._logger.error("oopies") user_info = payload.get("user") samples = payload.get("samples") facility = payload.get("facility") manifesto = payload.get("manifesto") institution = user.get("ldap", {}).get("actor_institution") request_uid = str(uuid4()) # create array of choices to insert into database # this is only for tracking the options presented purposes (possible debugging), # since only facility.get("choice") is critical information fse_choices = facility.get("digs") fse = [] for key in fse_choices: try: rank = int(key) except: pass else: fse.append(fse_choices[str(rank)]) request_id = None emailed = None # Create request query = """INSERT INTO `{}`.`Requests` (`uid`, `digs_id`, `fse`, `requester`, `institution`, `created` ) VALUES (\"{}\", (SELECT id from `{}`.`Digs` WHERE digs_core_number LIKE \"{}\"), \'{}\', "{}", \"{}\", NOW())""" \ .format(db_name, request_uid, db_name, facility.get("choice"), json.dumps(fse), user.get("ldap", {}).get("actor_username"), institution) with conn.cursor() as cursor: try: cursor.execute(query) conn.commit() except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() raise ApiSqlException(title=str(e), description=str(e), logger=self._logger, config=self._config, stacktrace=exc_value) else: query = """SELECT id from `{}`.`Requests` WHERE `uid` LIKE '{}'""".format(db_name, request_uid) try: cursor.execute(query) columns = [field[0] for field in cursor.description] res = cursor.fetchone() if res: request = dict(zip(columns, [res[0]])) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() raise ApiSqlException(title=str(e), description=str(e), logger=self._logger, config=self._config, stacktrace=exc_value) else: request_id = request.get("id") selected_facility = None query = """SELECT * FROM `{}`.`Digs` WHERE `digs_core_number` LIKE '{}'""".format(db_name, facility.get("choice")) try: cursor.execute(query) columns = [field[0] for field in cursor.description] res = cursor.fetchone() if res: selected_facility = dict(zip(columns, res)) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() raise ApiSqlException(title=str(e), description=str(e), logger=self._logger, config=self._config, stacktrace=exc_value) csv_manifest = [] res_manifesto = [] if request_id: csv_manifest.append('DIGS Sequencing Request Submission ID: R{}\n\n'.format(request_id)) # requester info block csv_manifest.append('Requester Contact Information\n') csv_manifest.append('Name,{}\n'.format(user_info.get("name"))) csv_manifest.append('Address,"{}, {} {} {}"\n'.format( user_info.get("street_address"), user_info.get("city"), user_info.get("state_province") if user_info.get("state_province") != "N/A" else "", selected_facility.get("zipcode"))) csv_manifest.append('Phone,{}\n'.format(user_info.get("daytime_phone"))) csv_manifest.append('Email,{}\n\n'.format(user_info.get("email"))) # facility info block csv_manifest.append('DIGS Facility Contact Information\n') csv_manifest.append('Name,{}\n'.format(selected_facility.get("contact_name"))) csv_manifest.append('Address,"{}, {} {} {}"\n'.format( selected_facility.get("shipping_address_street"), selected_facility.get("shipping_address_city"), selected_facility.get("shipping_address_state") if selected_facility.get("shipping_address_state") \ != "N/A" else "", selected_facility.get("shipping_address_zip"))) csv_manifest.append('Phone,{}\n'.format(selected_facility.get("contact_phone"))) csv_manifest.append('Email,{}\n\n'.format(selected_facility.get("contact_email"))) # sample table block csv_manifest.append("Sample Identifier,Extract Identifier,Sequencing Study Identifier,Submission ID," "Submission Type,Submitter Name,Submission Date,Project Identifier," "Contributing Institution,Virus Identifier,Strain Name,Influenza Subtype," "Host Species,Lab Host,Passage History,Pathogenicity," "Extract Material,Volume (µl),Concentration (ng/µl),Concentration Determined By," "Sequencing Technology,Analysis Type,Raw Sequences,Comments\n") request_contains_rna_sample = False for row, sample in enumerate(samples, 12): if sample.get("extract_material") == "Viral RNA": request_contains_rna_sample = True extract_id = "R{}_{}".format(request_id, sample["extract_id"]) query = """INSERT INTO `{}`.`Extracts` (`request_id`, `sample_id`, `extract_id`, `sequencing_study_identifier`, `submission_id`, `submission_type`, `submitter_name`, `submission_date`, `project_identifier`, `virus_identifier`, `influenza_subtype`, `host_species`, `lab_host`, `passage_history`, `pathogenicity`, `extract_material`, `volume`, `concentration`, `concentration_determined_by`, `sequencing_tecnhology`, `analysis_type`, `raw_sequences`, `comments`, `status`, `created`, `sample_identifier`) VALUES( {}, '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', {}, {}, '{}', '{}', '{}','{}', '{}', 'Requested', CURRENT_TIMESTAMP, '{}' )""". \ format(db_name, request_id, sample.get("sample_id"), extract_id, sample.get("sequencing_study_identifier"), sample.get("submission_id"), sample.get("submission_type"), sample.get("submitter_name"), sample.get("submission_date"), sample.get("project_identifier"), sample.get("virus_identifier"), sample.get("influenza_subtype"), sample.get("host_species"), sample.get("lab_host"), sample.get("passage_history"), sample.get("pathogenicity"), sample.get("extract_material"), sample.get("volume"), sample.get("concentration"), sample.get("concentration_determined_by"), json.dumps(sample.get("sequencing_technology")), json.dumps(sample.get("analysis_type")), sample.get("raw_sequences", '0'), sample.get("comments"), sample.get("sample_identifier")) try: res = cursor.execute(query) if res: conn.commit() except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() raise ApiSqlException(title=str(e), description=str(e), logger=self._logger, config=self._config, stacktrace=exc_value) else: analysis_type = " / ".join( [analysis for analysis in sample["analysis_type"] if sample["analysis_type"][analysis]]) sequencing_technology = " or ".join( [tech for tech in sample["sequencing_technology"] if sample["sequencing_technology"][tech]]) csv_manifest.append("\"{}\",\"{}\",\"{}\",\"{}\t\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\"," "\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\",\"{}\"," "\"{}\",\"{}\",\"{}\",\"{}\"\n".format( sample.get("sample_identifier"), extract_id, sample.get("sequencing_study_identifier"), sample.get("submission_id", ""), sample.get("submission_type", ""), sample.get("submitter_name", ""), sample.get("submission_date", ""), sample.get("project_identifier"), sample.get("contributing_institution", ""), sample.get("virus_identifier"), sample.get("strain_name"), sample.get("influenza_subtype"), sample.get("host_species"), sample.get("lab_host"), sample.get("passage_history"), sample.get("pathogenicity"), sample.get("extract_material"), sample.get("volume"), sample.get("concentration"), sample.get("concentration_determined_by"), sequencing_technology, analysis_type, sample.get("raw_sequences", "N"), sample.get("comments", ""))) res_manifesto.append([sample.get("sample_identifier"), sample.get("extract_id"), sample.get("sequencing_study_identifier"), sample.get("submission_id", ""), sample.get("submission_type", ""), sample.get("submitter_name", ""), sample.get("submission_date", ""), sample.get("project_identifier"), sample.get("contributing_institution", ""), sample.get("virus_identifier"), sample.get("strain_name"), sample.get("influenza_subtype"), sample.get("host_species"), sample.get("lab_host"), sample.get("passage_history"), sample.get("pathogenicity"), sample.get("extract_material"), sample.get("volume"), sample.get("concentration"), sample.get("concentration_determined_by"), sequencing_technology, analysis_type, sample.get("raw_sequences", "N"), sample.get("comments", "")]) # wb.save("manifest.xls") with SpooledTemporaryFile() as fh: # writer = csv.writer(fh, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) fh.writelines([x.encode('utf-8') for x in csv_manifest]) fh.seek(0) # with open("swt/scripts/request_{}.{}".format(request_id, "csv"), 'w') as file: # for line in csv_manifest: # file.write(line) aws_configuration = { 'aws_access_key_id': self._config.get('aws', 'aws_access_key_id'), 'aws_secret_access_key': self._config.get('aws', 'aws_secret_access_key'), 'region_name': self._config.get('aws', 'aws_region') } _s3 = S3(credentials=aws_configuration, logger=self._logger) filename = "request_{}.{}".format(request_id, "csv") bucket = self._config.get("aws", "s3_bucket") # bucket = "swt-prod" key = "manifest-files/" + filename pre_signed_url = _s3.upload(bucket, key, fh) if not pre_signed_url: return {"status": False, "statusText": "Error uploading manifest to aws"} rna_warning_msg = """<br><p><u>Notice</u>: This Sequencing Request includes RNA-based samples. Please handle accordingly when shipping your samples.</p>""" \ if request_contains_rna_sample else "" conn = boto.ses.connect_to_region(**aws_configuration) email_from = '*****@*****.**' user_email = user_info.get("email") facility_email = user_email if env == "prod": facility_email = facility.get("digs", {}).get("contact_info", {})\ .get(facility.get("choice")).get("email") email_body_facility = EXTRACT_EMAIL_FACILITY_BODY.format(request_id, user_info.get("name"), "{}, {} {} {}".format( user_info.get("street_address"), user_info.get("city"), user_info.get("state_province") \ if user_info.get("state_province") \ != "N/A" else "", user_info.get("zipcode")), user_info.get("daytime_phone"), user_info.get("email"), EXTRACT_EMAIL_SIGNATURE, rna_warning_msg) emailMsg = MIMEMultipart() emailMsg['Subject'] = EXTRACT_EMAIL_FACILITY_SUBJECT emailMsg['From'] = email_from emailMsg['To'] = facility_email emailMsg.preamble = 'Multipart message.\n' part = MIMEText(email_body_facility, 'html') emailMsg.attach(part) part = MIMEBase('application', 'octet-stream') fh.seek(0) part.set_payload(fh.read()) encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="shipping_manifest.csv"') emailMsg.attach(part) emailed_facility = conn.send_raw_email(emailMsg.as_string(), source=emailMsg['From'], destinations=[emailMsg['To']]) email_body_requester = EXTRACT_EMAIL_REQUESTER_BODY.format(user_info.get("name"), request_id, pre_signed_url, selected_facility.get( "digs_core_name"), selected_facility.get( "digs_core_name"), EXTRACT_EMAIL_SIGNATURE, rna_warning_msg) emailed_requester = conn.send_email(email_from, EXTRACT_EMAIL_REQUESTER_SUBJECT, None, to_addresses=user_info.get("email"), format="html", html_body=email_body_requester) email_failed = not emailed_facility or not emailed_requester if email_failed: raise ApiSqlException( title="Extracts have been saved, but there was a problem emailing the DIGS facility. Please contact the DPCC", description="Extracts have been saved, but there was a problem emailing the DIGS facility. Please contact the DPCC", logger=self._logger, config=self._config) return {"status": True, "request_id": request_id, "manifesto": res_manifesto}
def create_msg(): """ Will get args from demisto object Return: a string representation of the message, to, cc, bcc """ # Collect all parameters to = argToList(demisto.getArg('to')) cc = argToList(demisto.getArg('cc')) bcc = argToList(demisto.getArg('bcc')) additional_header = argToList(demisto.getArg('additionalHeader')) subject = demisto.getArg('subject') or '' body = demisto.getArg('body') or '' htmlBody = demisto.getArg('htmlBody') or '' replyTo = demisto.getArg('replyTo') templateParams = template_params() if templateParams: body = body.format(**templateParams) htmlBody = htmlBody.format(**templateParams) # Basic validation - we allow pretty much everything but you have to have at least a recipient # We allow messages without subject and also without body if not to and not cc and not bcc: return_error_mail_sender('You must have at least one recipient') attachments = collect_attachments() attachments.extend(collect_manual_attachments()) # Let's see what type of message we are talking about if not htmlBody: # This is a simple text message - we cannot have CIDs here if len(attachments) > 0: # This is multipart - default is mixed msg = MIMEMultipart() # type: Message msg.preamble = 'The message is only available on a MIME-aware mail reader.\n' msg.attach(MIMEText(body, 'plain', UTF_8)) for att in attachments: handle_file(msg, att['name'], att['maintype'], att['subtype'], None, att['data']) else: # Just text, how boring msg = MIMEText(body, 'plain', UTF_8) else: htmlBody, htmlAttachments = handle_html(htmlBody) attachments += htmlAttachments if len(attachments) > 0: msg = MIMEMultipart() msg.preamble = 'The message is only available on a MIME-aware mail reader.\n' if body: alt = MIMEMultipart('alternative') alt.attach(MIMEText(body, 'plain', UTF_8)) alt.attach(MIMEText(htmlBody, 'html', UTF_8)) msg.attach(alt) else: msg.attach(MIMEText(htmlBody, 'html', UTF_8)) for att in attachments: handle_file(msg, att['name'], att['maintype'], att['subtype'], att['cid'], att['data']) else: if body: msg = MIMEMultipart('alternative') msg.preamble = 'The message is only available on a MIME-aware mail reader.\n' msg.attach(MIMEText(body, 'plain', UTF_8)) msg.attach(MIMEText(htmlBody, 'html', UTF_8)) else: msg = MIMEText(htmlBody, 'html', UTF_8) # Add the relevant headers to the most outer message msg['Subject'] = header(subject) msg['From'] = header(demisto.getParam('from')) if replyTo: msg['Reply-To'] = header(replyTo) if to: msg['To'] = header(','.join(to)) if cc: msg['CC'] = header(','.join(cc)) if additional_header: for h in additional_header: header_name_and_value = h.split('=', 1) msg[header_name_and_value[0]] = header(header_name_and_value[1]) # Notice we should not add BCC header since Python2 does not filter it return msg.as_string(), to, cc, bcc
def sendHTMLMail(self, mail_to, mail_from, reply_to, mail_subject, html_message, text_alternative, images=None, css=None): """ Send an HTML email message, encoded in a MIME/multipart message. The images and css are included in the message, and should be provided separately. @type mail_to: string or list of strings @type mail_from: string @type reply_to: string @type mail_subject: string @type html_message: string @type text_alternative: string @type images: list of strings @type css: string @param mail_to: a valid recipient email addresses. @param mail_from: a valid sender email address. @param reply_to: a valid email address for the (potential) replies. @param html_message: the actual payload, body of the mail @param text_alternative: plain-text version of the mail body @param images: the images that are referenced in the HTML body. These should be available as files on the filesystem in the directory where the script runs. Caveat: assume jpeg image type. @param css: CSS definitions """ # Create message container - the correct MIME type is multipart/alternative. msg_root = MIMEMultipart('alternative') msg_root['Subject'] = mail_subject msg_root['From'] = mail_from msg_root['To'] = mail_to if reply_to is None: reply_to = mail_from msg_root['Reply-to'] = reply_to msg_root.preamble = 'This is a multi-part message in MIME format. If your email client does not support this' \ '(correctly), the first part is the plain text version.' # Create the body of the message (a plain-text and an HTML version). if images is not None: html_message = self.replace_images_cid(html_message, images) # Record the MIME types of both parts - text/plain and text/html_message. msg_plain = MIMEText(text_alternative, 'plain') msg_html = MIMEText(html_message, 'html_message') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg_root.attach(msg_plain) msg_alt = MIMEMultipart('related') msg_alt.attach(msg_html) if css is not None: msg_html_css = MIMEText(css, 'css') msg_html_css.add_header('Content-ID', '<newsletter.css>') msg_alt.attach(msg_html_css) if images is not None: for im in images: image_fp = open(im, 'r') msg_image = MIMEImage(image_fp.read(), 'jpeg') # FIXME: for now, we assume jpegs image_fp.close() msg_image.add_header('Content-ID', "<%s>" % im) msg_alt.attach(msg_image) msg_root.attach(msg_alt) self._send(mail_from, mail_to, mail_subject, msg_root)
from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.text import MIMEText emailfrom = "*****@*****.**" emailto = "*****@*****.**" fileToSend = "dosyaadı.tar" username = "******" password = "******" msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = emailto msg["Subject"] = "deneme konu" msg.preamble = "hshhs" ctype, encoding = mimetypes.guess_type(fileToSend) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(fileToSend) # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(fileToSend, "rb") attachment = MIMEImage(fp.read(), _subtype=subtype)
def workflow_action_retract_ar(self): workflow = getToolByName(self.context, 'portal_workflow') # AR should be retracted # Can't transition inactive ARs if not isActive(self.context): message = _('Item is inactive.') self.context.plone_utils.addPortalMessage(message, 'info') self.request.response.redirect(self.context.absolute_url()) return # 1. Copies the AR linking the original one and viceversa ar = self.context newar = self.cloneAR(ar) # 2. The old AR gets a status of 'invalid' workflow.doActionFor(ar, 'retract_ar') # 3. The new AR copy opens in status 'to be verified' changeWorkflowState(newar, 'bika_ar_workflow', 'to_be_verified') # 4. The system immediately alerts the client contacts who ordered # the results, per email and SMS, that a possible mistake has been # picked up and is under investigation. # A much possible information is provided in the email, linking # to the AR online. laboratory = self.context.bika_setup.laboratory lab_address = "<br/>".join(laboratory.getPrintAddress()) mime_msg = MIMEMultipart('related') mime_msg['Subject'] = t( _("Erroneus result publication from ${request_id}", mapping={"request_id": ar.getRequestID()})) mime_msg['From'] = formataddr((encode_header(laboratory.getName()), laboratory.getEmailAddress())) to = [] contact = ar.getContact() if contact: to.append( formataddr((encode_header(contact.Title()), contact.getEmailAddress()))) for cc in ar.getCCContact(): formatted = formataddr( (encode_header(cc.Title()), cc.getEmailAddress())) if formatted not in to: to.append(formatted) managers = self.context.portal_groups.getGroupMembers('LabManagers') for bcc in managers: user = self.portal.acl_users.getUser(bcc) if user: uemail = user.getProperty('email') ufull = user.getProperty('fullname') formatted = formataddr((encode_header(ufull), uemail)) if formatted not in to: to.append(formatted) mime_msg['To'] = ','.join(to) aranchor = "<a href='%s'>%s</a>" % (ar.absolute_url(), ar.getRequestID()) naranchor = "<a href='%s'>%s</a>" % (newar.absolute_url(), newar.getRequestID()) addremarks = ('addremarks' in self.request and ar.getRemarks()) \ and ("<br/><br/>" + _("Additional remarks:") + "<br/>" + ar.getRemarks().split("===")[1].strip() + "<br/><br/>") \ or '' sub_d = dict(request_link=aranchor, new_request_link=naranchor, remarks=addremarks, lab_address=lab_address) body = Template( "Some errors have been detected in the results report " "published from the Analysis Request $request_link. The Analysis " "Request $new_request_link has been created automatically and the " "previous has been invalidated.<br/>The possible mistake " "has been picked up and is under investigation.<br/><br/>" "$remarks $lab_address").safe_substitute(sub_d) msg_txt = MIMEText(safe_unicode(body).encode('utf-8'), _subtype='html') mime_msg.preamble = 'This is a multi-part MIME message.' mime_msg.attach(msg_txt) try: host = getToolByName(self.context, 'MailHost') host.send(mime_msg.as_string(), immediate=True) except Exception as msg: message = _( 'Unable to send an email to alert lab ' 'client contacts that the Analysis Request has been ' 'retracted: ${error}', mapping={'error': safe_unicode(msg)}) self.context.plone_utils.addPortalMessage(message, 'warning') message = _('${items} invalidated.', mapping={'items': ar.getRequestID()}) self.context.plone_utils.addPortalMessage(message, 'warning') self.request.response.redirect(newar.absolute_url())
def create_email_message( self, fromaddr, toaddrs, ccaddrs, subject, priority, include_userdata=False, stack_trace="", comments="", include_environment=True, ): """Format a bug report email from the log files.""" from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText message = MIMEMultipart() message["Subject"] = "%s [priority=%s]" % (subject, priority) message["To"] = ", ".join(toaddrs) message["Cc"] = ", ".join(ccaddrs) message["From"] = fromaddr message.preamble = ( "You will not see this in a MIME-aware mail " "reader.\n" ) message.epilogue = " " # To guarantee the message ends with a newline # First section is simple ASCII data ... m = [] m.append("Bug Report") m.append("==============================") m.append("") if len(comments) > 0: m.append("Comments:") m.append("========") m.append(comments) m.append("") if len(stack_trace) > 0: m.append("Stack Trace:") m.append("===========") m.append(stack_trace) m.append("") msg = MIMEText("\n".join(m)) message.attach(msg) # Include the log file ... logtext = self.whole_log_text() msg = MIMEText(logtext) msg.add_header( "Content-Disposition", "attachment", filename="logfile.txt" ) message.attach(msg) # Include the environment variables ... # FIXME: ask the user, maybe? if include_environment: # Transmit the user's environment settings as well. Main purpose # is to work out the user name to help with following up on bug # reports and in future we should probably send less data. entries = [] for key, value in sorted(os.environ.items()): entries.append("%30s : %s\n" % (key, value)) msg = MIMEText("".join(entries)) msg.add_header( "Content-Disposition", "attachment", filename="environment.txt" ) message.attach(msg) if include_userdata and len(self.mail_files) != 0: f = BytesIO() zf = zipfile.ZipFile(f, "w") for mf in self.mail_files: mf(zf) zf.close() msg = MIMEApplication(f.getvalue()) msg.add_header( "Content-Disposition", "attachment", filename="userdata.zip" ) message.attach(msg) return message
command = "raspistill -w 640 -h 640 -vf -hf -o " + fName os.system(command) # Email info usr = '******' pwd = 'Grand123$' # Destination email information toAddr = '*****@*****.**' fromAddr = usr sub = 'Image Recorded at ' + pic_time msg = MIMEMultipart() msg['Subject'] = sub msg['From'] = fromAddr msg['to'] = toAddr msg.preamble = 'Image Recorded at ' + pic_time # Email text body = MIMEText('Image Recorded at ' + pic_time) msg.attach(body) # Attach Image fp = open(fName, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) # Send Email s = smtplib.SMTP('smtp.gmail.com', 587) s.ehlo()
emailList = eval(f.read()) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s: s.login('*****@*****.**', 'takemetonewheights$2020') for e in emailList: email = e['Email'] print('Sending to', email) strTo = email strFrom = '*****@*****.**' msgRoot = MIMEMultipart('related') msgRoot['Subject'] = '[Enchanted Mirror] Here are your photos!' msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText( 'Check out our www.facebook.com/enchantedphotoboothoc/') msgAlternative.attach(msgText) print(e) photoPaths = e['PhotoPath'] print(photoPaths) imgTags = [ '<img src="cid:image{}">'.format(i) for i, x in enumerate(photoPaths) ] for i, filePath in enumerate(photoPaths):
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()