def send_html(cls, to, topic, message): config = ApplicationConfig.get_current_config() email = MIMEMultipart('alternative') email['Subject'] = topic email['From'] = config.google_user_email email['To'] = to email.attach(MIMEText(message,'html', 'utf-8')) formatted_mail = email.as_string() messageFile = StringIO(formatted_mail) resultDeferred = Deferred() senderFactory = ESMTPSenderFactory( config.google_user_email, # user config.google_user_password, # secret config.google_user_email, # from to, # to messageFile, # message resultDeferred, # deferred contextFactory=cls.contextFactory) reactor.connectTCP(cls.SMTP_SERVER, cls.SMTP_PORT, senderFactory) return resultDeferred
def do_send_mail(self, to, subject, text, sleep=10, actually_send_mail=False): from email.header import Header from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart msg = MIMEText(text, 'plain', 'utf-8') sender_email = "*****@*****.**" receiver_email = to email = MIMEMultipart('mixed') email['From'] = sender_email email['To'] = receiver_email email['Subject'] = Header(subject, 'utf-8') msg.set_payload(text.encode('utf-8')) email.attach(msg) message = email.as_string() if False: message = 'Subject: {}\n\n{}'.format(subject, text) if actually_send_mail: self.server.sendmail(sender_email, receiver_email, message) time.sleep(sleep) print('Mail sent')
def send_with_file(cls, to, topic, message, file_path): config = ApplicationConfig.get_current_config() email = MIMEMultipart() email['Subject'] = topic email['From'] = config.google_user_email email['To'] = to part = MIMEBase('application', "octet-stream") part.set_payload(open(file_path, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % file_path.split('/')[-1]) email.attach(part) email.attach(MIMEText(message)) formatted_mail = email.as_string() messageFile = StringIO(formatted_mail) resultDeferred = Deferred() senderFactory = ESMTPSenderFactory( config.google_user_email, # user config.google_user_password, # secret config.google_user_email, # from to, # to messageFile, # message resultDeferred, # deferred contextFactory=cls.contextFactory) reactor.connectTCP(cls.SMTP_SERVER, cls.SMTP_PORT, senderFactory) return resultDeferred
def buildEmail(user, receiver, initialDate, finalDate, filePath): locale.setlocale(locale.LC_TIME, 'es-co') email = MIMEMultipart() if (initialDate.month == finalDate.month): dateText = "{} al {} de {}".format(initialDate.day, finalDate.day, initialDate.strftime("%B")) subject = "Factura {} {} - {} {}".format( initialDate.strftime("%B").capitalize(), initialDate.day, finalDate.day, initialDate.year) else: dateText = "{} de {} al {} de {}".format(initialDate.day, initialDate.strftime("%B"), finalDate.day, finalDate.strftime("%B")) subject = "Factura {} {} - {} {} {}".format( initialDate.strftime("%B").capitalize(), initialDate.day, finalDate.strftime("%B").capitalize(), finalDate.day, initialDate.year) body = """Hola Alex, Te envío la factura correspondiente a la semana del {}. Quedo atento a tus comentarios. Muchas gracias. (Mensaje autogenerado por el invoiceGenerator :D)""".format( dateText) email['From'] = user email['Subject'] = subject email['To'] = receiver email.attach(MIMEText(body, "plain")) with open(filePath, "rb") as attachment: # Add file as application/octet-stream # Email client can usually download this automatically as attachment part = MIMEBase( "application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet") part.set_payload(attachment.read()) # Encode file in ASCII characters to send by email encoders.encode_base64(part) # Add header as key/value pair to attachment part part.add_header( "Content-Disposition", f"attachment; filename= {os.path.basename(filePath)}", ) # Add attachment to message and convert message to string email.attach(part) text = email.as_string() # print(email) return text
def sendEmail(subject, body, sender, receiver, password): logging.info('sending email...') # Create the email head (sender, receiver, and subject) email = MIMEMultipart() email["From"] = sender email["To"] = receiver email["Subject"] = subject # Add body and attachment to email email.attach(MIMEText(body, 'plain')) # Create SMTP session for sending the mail session = smtplib.SMTP('smtp.gmail.com', 587) session.starttls() session.login(sender, password) text = email.as_string() session.sendmail(sender, receiver, text) session.quit() # print out email logging.info(email['To']) logging.info(email['From']) logging.info(email['Subject']) logging.info(body)
def sending(): # assign key email aspects to variables for easier future editing subject = "Betreff" body = "Inhalt" sender_email = "*****@*****.**" receiver_email = ["*****@*****.**", "*****@*****.**"] file = "report.pdf" # in the same directory as script password = "******" # Create the email head (sender, receiver, and subject) email = MIMEMultipart() email["From"] = sender_email email["To"] = ", ".join(receiver_email) email["Subject"] = subject # Add body and attachment to email email.attach(MIMEText(body, "plain")) attach_file = open(file, "rb") # open the file report = MIMEBase("application", "octate-stream") report.set_payload((attach_file).read()) encoders.encode_base64(report) #add report header with the file name report.add_header("Content-Decomposition", "attachment", filename = file) email.attach(report) #Create SMTP session for sending the mail session = smtplib.SMTP('smtp.strato.de', 587) #use strato with port session.starttls() #enable security session.login(sender_email, password) #login with mail_id and password text = email.as_string() session.sendmail(sender_email, receiver_email, text) session.quit() print('Mail Sent')
def createEmail(sender, recipient, subject, body): # create headers email = MIMEMultipart() email['From'] = sender email['To'] = recipient email['Subject'] = subject email.attach(MIMEText(body[:-1], 'plain')) #body[:-1] gets rid of extra newLine print("Email Created successfully") return email
def render_template(self, render_data): template_name = render_data.get("name", "") template = self.templates.get(template_name, None) if not template: raise TemplateDoesNotExist("Invalid Template Name.") template_data = render_data.get("data") try: template_data = json.loads(template_data) except ValueError: raise InvalidRenderingParameterException( "Template rendering data is invalid") var, are_variables_present = are_all_variables_present( template, template_data) if not are_variables_present: raise MissingRenderingAttributeException(var) subject_part = template["subject_part"] text_part = template["text_part"] html_part = template["html_part"] for key, value in template_data.items(): subject_part = str.replace(str(subject_part), "{{%s}}" % key, value) text_part = str.replace(str(text_part), "{{%s}}" % key, value) html_part = str.replace(str(html_part), "{{%s}}" % key, value) email = MIMEMultipart("alternative") mime_text = MIMEBase("text", "plain;charset=UTF-8") mime_text.set_payload(text_part.encode("utf-8")) encode_7or8bit(mime_text) email.attach(mime_text) mime_html = MIMEBase("text", "html;charset=UTF-8") mime_html.set_payload(html_part.encode("utf-8")) encode_7or8bit(mime_html) email.attach(mime_html) now = datetime.datetime.now().isoformat() rendered_template = "Date: %s\r\nSubject: %s\r\n%s" % ( now, subject_part, email.as_string(), ) return rendered_template
def _parse(self, **kw): """ Format an outgoing email. """ email = MIMEMultipart() # meta email['From'] = kw.get('from_') email['To'] = kw.get('to_') email['Subject'] = kw.get('subject', '') email['Cc'] = kw.get('cc', '') # body text = MIMEText(kw.get('body'), kw.get('message_type', 'plain'), kw.get('message_encoding', 'us-ascii')) email.attach(text) return email
def _parse(self, **kw): """ Format an outgoing email. """ email = MIMEMultipart() # meta email['From'] = kw.get('from_') email['To'] = kw.get('to_') email['Subject'] = kw.get('subject', '') email['Cc'] = kw.get('cc', '') # body text = MIMEText( kw.get('body'), kw.get('message_type', 'plain'), kw.get('message_encoding', 'us-ascii') ) email.attach(text) return email
def notify(issue): ''' Send an email when the scraper is force quitted or data has been contaminated -:param issue: 'forcequit' or 'contamination' to specify the content of the email ''' subject = "Craiglist Scraper Issue Report" body = body_text(issue) sender_email = "*****@*****.**" #receiver_email = "*****@*****.**" receiver_email = "*****@*****.**" file = "util/attachments/instructions.pdf" password = "******" # Create the email head (sender, receiver, and subject) email = MIMEMultipart() email["From"] = sender_email email["To"] = receiver_email email["Subject"] = subject # Add body and attachment to email email.attach(MIMEText(body, "plain")) attach_file = open(file, "rb") # open the file report = MIMEBase("application", "octate-stream") report.set_payload((attach_file).read()) encoders.encode_base64(report) #add report header with the file name report.add_header("Content-Disposition", "attachment", filename="instructions.pdf") email.attach(report) #Create SMTP session for sending the mail session = smtplib.SMTP("smtp.mail.yahoo.com", 587) #use gmail with port session.starttls() #enable security session.login(sender_email, password) #login with mail_id and password text = email.as_string() session.sendmail(sender_email, receiver_email, text) session.quit() print("A notification of the error has been sent to: " + receiver_email)
def submit(): #geotags = request.form.get('geotags', '') theRequest = request.form.get('request', 'default request') geotag = '12.345, 67.8910' the_email = session['email'] print("we got here!") geotags.insert_one({ 'email': the_email, 'geotag': geotag, 'request': theRequest }) print("got here") print('The test is running succesfully') #print('Mail Sent') # assign key email aspects to variables for easier future editing subject = "Your Suggestion" message = request.form.get("message", "default value") print(message) body = "Hi there dear user,\n\nWe heard that you expressed interest in someone opening a(n)" + message + "! We'll send another email to update you if any " + message + " opens nearby." sender_email = "*****@*****.**" #session['email'] = session['email'] print('session[email] is: ', session['email']) email_test = session['email'] print('email_test is: ', email_test) receiver_email = email_test password = "******" # Create the email head (sender, receiver, and subject) email = MIMEMultipart() email["From"] = sender_email email["To"] = receiver_email email["Subject"] = subject email.attach(MIMEText(body, "plain")) #Create SMTP session for sending the mail session1 = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port session1.starttls() #enable security session1.login(sender_email, password) #login with mail_id and password text = email.as_string() session1.sendmail(sender_email, receiver_email, text) session1.quit() return 'success'
def send_error_report(_from, _to, _subject, _uploaddatetime, _uploadtype, _error): if _uploadtype == 'vehicle': ut = 'Fahrzeugdaten' if _uploadtype == 'his': ut = 'Reparaturarbeiten' if _uploadtype == 'workshop': ut = 'Werkstattdaten' ctx = { 'title': _subject, 'uploaddate': _uploaddatetime.strftime('%d.%m.%Y'), 'uploadtime': _uploaddatetime.strftime('%H:%M:%S'), 'uploadtype': ut, } htmly = get_template('email-templates/error_report.html') html_content = htmly.render(ctx) email = EmailMessage(_subject, html_content, _from, _to) if _error: a = create_attachment(_error) email.attach('Importfehler.csv', a.getvalue(), 'text/csv') email.content_subtype = 'html' email.send() return None
def send_mail(receiver_email): # Create the email head (sender, receiver, and subject) email = MIMEMultipart() email["From"] = sender_email email["To"] = receiver_email email["Subject"] = subject # Add body and attachment to email email.attach(MIMEText(body, "plain")) #attach_file = open(file, "rb") # open the file #report = MIMEBase("application", "octate-stream") #report.set_payload((attach_file).read()) #encoders.encode_base64(report) #add report header with the file name #report.add_header("Content-Decomposition", "attachment", filename = file) #email.attach(report) #Create SMTP session for sending the mail session = smtplib.SMTP('smtp.zoho.com', 587) #use gmail with port session.starttls() #enable security session.login(sender_email, password) #login with mail_id and password text = email.as_string() session.sendmail(sender_email, receiver_email, text) session.quit() print('Mail Sent to: ' + receiver_email + ' successful!')
def send_email_with_attachments(): # Settings of sender's server host = 'smtp.aliyun.com' sender = '*****@*****.**' user = '******' password = input('Please type your password: '******'*****@*****.**'] # Make content of email subject = 'Python send email with attachments' with open('./dataset/out.html', 'r') as f: content = MIMEText(f.read(), 'html', 'utf-8') content['Content-Type'] = 'text/html' print('Loaded content.') # Make txt attachment with open('./dataset/in.md', 'r') as f: txt = MIMEText(f.read(), 'plain', 'utf-8') txt['Content-Type'] = 'application/octet-stream' txt['Content-Disposition'] = 'attachment;filename="in.md"' print('Loaded txt attachment file.') # Make image attachment with open('./dataset/pic.png', 'rb') as f: img = MIMEImage(f.read()) img['Content-Type'] = 'application/octet-stream' img['Content-Disposition'] = 'attachment;filename="pic.png"' print('Loaded image attachment file.') # Attach content & attachments to email email = MIMEMultipart() email.attach(content) email.attach(txt) email.attach(img) # Settings of the email string email['Subject'] = subject email['From'] = sender email['To'] = to[0] msg = email.as_string() # Login the sender's server print('Logging with server...') smtpObj = smtplib.SMTP() smtpObj.connect(host, 25) smtpObj.login(user, password) print('Login successful.') # Send email smtpObj.sendmail(sender, to, msg) smtpObj.quit() print('Email has been sent')
c.drawString(5, 630, 'Report generated by Python') c.showPage() c.save() subject = "Weekly Report" body = "This is an email with the desired report attached" sender_email = "*****@*****.**" receiver_email = "example.com" file = "example.pdf" # in the same directory as script password = '******' email = MIMEMultipart() email["From"] = sender_email email["To"] = receiver_email email["Subject"] = subject email.attach(MIMEText(body, "plain")) attach_file = open(file, "rb") # open the file report = MIMEBase("application", "octate-stream") report.set_payload((attach_file).read()) encoders.encode_base64(report) # add report header with the file name report.add_header("Content-Decomposition", "attachment", filename=file) email.attach(report) session = smtplib.SMTP('smtp.gmail.com', 587) # use gmail with port session.starttls() # enable security session.login(sender_email, password) # login with mail_id and password text = email.as_string() session.sendmail(sender_email, receiver_email, text) session.quit()
def send_email(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`. """ import os import json import email, smtplib, ssl from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import datetime as dt # to work with date, time import sys request_json = request.get_json() #--> get the request json if request_json and 'subject' in request_json: print('subject ==> {}'.format(request_json['subject'])) if request_json and 'receiver_email' in request_json: print('receiver_email ==> {}'.format(request_json['receiver_email'])) ## 1A - Take input from request json receiver_email = request_json['receiver_email'] subject = request_json['subject'] ## 1B - Get ENV set in Cloud #sender_email = os.getenv('SENDER_EMAIL') ## PLEASE MEMBER TO SET THE ENV VARIABLES IN YOUR CLOUD FUNC sender_email = os.environ.get('SENDER_EMAIL') password = os.environ.get('PWD_EMAIL') print('=== Step 1: Get Input') ## 2 - Email Set email = MIMEMultipart() email["From"] = sender_email email["To"] = receiver_email email["Subject"] = subject ## 3 - Email Contents # We use html, you can convert word to html: https://wordtohtml.net/ html1 = """ <html> <h1><strong>Hello World</strong></h1> <body> <p>Hi!<br> How are you?<br> Here is the <a href="https://docs.python.org/3.4/library/email-examples.html">link</a> you wanted. </p> </body> </html> """ html2 = """ <html> Email sent at <b>{}</b><br> </html> """.format(dt.datetime.now().isoformat()) text3 = '--- End ----' # Combine parts part1 = MIMEText(html1, 'html') part2 = MIMEText(html2, 'html') part3 = MIMEText(text3, 'plain') email.attach(part1) email.attach(part2) email.attach(part3) print('=== Step 2: Prep Contents') ## 4 - Create SMTP session for sending the mail try: session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port session.starttls() #enable security print('=== Step 3: Enable Security') session.login(sender_email, password) #login with mail_id and password print('=== Step 4: Login Success!') text = email.as_string() session.sendmail(sender_email, receiver_email, text) session.quit() print('DONE! Mail Sent from {} to {}'.format(sender_email, receiver_email)) message = 'DONE! Mail Sent from {} to {}'.format(sender_email, receiver_email) status = 'OK' except: print('=== ERROR: {}'.format(sys.exc_info()[0])) message = 'ERROR: {}'.format(sys.exc_info()[0]) status = 'FAIL' out = {'status': status, 'message': message} headers= { 'Access-Control-Allow-Origin': '*', 'Content-Type':'application/json' } return (json.dumps(out), 200, headers)