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 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 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 sendDailyMail(messages, server): # import smtplib srv = smtplib.SMTP(server, 25) for email in messages: print(email.as_string()) for email in messages: try: # srv.sendmail(email.as_string()) srv.sendmail(email['From'], email['To'], email.as_string()) print(email) print("Successfully sent email") except: print("Error: unable to send email") print(email) srv.quit()
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 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 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')
def dkim_verify(self, email): # verify dkim dkim_obj = dkim.DKIM(email.as_string()) try: verified = dkim_obj.verify() except dkim.ValidationError as e: return False except dkim.KeyFormatError as e: return False except Exception as e: print e return False return verified
def send_bug_report(address, message, bug_report): """Send a bug report by email.""" body = ("From: %s\n\n %s\n\n" % (address, message)) + 30*"=" + "\n\n" + bug_report email = MIMEText(asciify(body)) email["Subject"] = "MapTiler bug report" email["From"] = FROM_ADDRESS email["To"] = TO_ADDRESS server = smtplib.SMTP(SMTP_SERVER) server.sendmail(FROM_ADDRESS, TO_ADDRESS, email.as_string()) server.quit()
def send_bug_report(address, message, bug_report): """Send a bug report by email.""" body = ("From: %s\n\n %s\n\n" % (address, message)) + 30 * "=" + "\n\n" + bug_report email = MIMEText(asciify(body)) email["Subject"] = "MapTiler bug report" email["From"] = FROM_ADDRESS email["To"] = TO_ADDRESS server = smtplib.SMTP(SMTP_SERVER) server.sendmail(FROM_ADDRESS, TO_ADDRESS, email.as_string()) server.quit()
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 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 send(cls, to, topic, message, sender_name=None, cc=None, replay_to=None): """ Send an email with message to given address. This is an asynchronous call. @return: deferred """ config = ApplicationConfig.get_current_config() user = config.google_user_email email_addr = user if sender_name: email_addr = formataddr((sender_name, email_addr)) secret = config.google_user_password SenderFactory = ESMTPSenderFactory email = MIMEText(message, _charset='utf-8') email['Subject'] = topic email['From'] = email_addr email['To'] = to if cc: email['Cc'] = cc if replay_to: email['Reply-To'] = replay_to formatted_mail = email.as_string() messageFile = StringIO(formatted_mail) resultDeferred = Deferred() senderFactory = SenderFactory( user, # user secret, # secret user, # from to, # to messageFile, # message resultDeferred, # deferred contextFactory=cls.contextFactory) reactor.connectTCP(cls.SMTP_SERVER, cls.SMTP_PORT, senderFactory) return resultDeferred
def sendEmail(self): email = EmailMessage() email["From"] = self.sender_email email["To"] = self.receiver_email email["Subject"] = self.subject attach_file = open(self.file, "r+") # open the file email.set_content(attach_file.read()) attach_file.close() #Create SMTP session for sending the mail session = smtplib.SMTP_SSL('smtp.googlemail.com', 465) #use gmail with port session.ehlo() try: session.login(self.sender_email, self.password) except SMTPAuthenticationError: print('SMTPAuthenticationError') text = email.as_string() #session.send_message(email) session.quit() print('Mail Sent')
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 sign_email(email, domain='hvornum.se', domain_priv_key="/etc/pempath/keys/hvornum.se.pem", selector='default'): if not domain: domain = domain if type(selector) != bytes: selector = bytes(selector, 'UTF-8') if type(domain) != bytes: domain = bytes(domain, 'UTF-8') if not os.path.isfile(domain_priv_key): logger.error(f'Missing private DKIM key: {domain_priv_key}') return None with open(domain_priv_key, 'rb') as fh: dkim_private_key = fh.read() sig = dkim.sign(message=bytes(email.as_string(), 'UTF-8'), selector=selector, domain=domain, privkey=dkim_private_key, include_headers=["To", "From", "Subject"]) return sig.lstrip(b"DKIM-Signature: ").decode('UTF-8')
def send_email_in_html(): # Settings of sender's server host = 'smtp.aliyun.com' sender = '*****@*****.**' user = '******' password = input('Please type your password: '******'*****@*****.**'] # host = 'smtp.sina.com' # sender = '*****@*****.**' # user = '******' # password = input('Please type your password: '******'*****@*****.**'] # Login the sender's server print('Logging with server...') smtpObj = smtplib.SMTP() smtpObj.connect(host, 25) smtpObj.login(user, password) print('Login successful.') # Content of email subject = 'Python send html email test33' with open('./dataset/out.html', 'r') as f: content = f.read() # Settings of the email string email = MIMEText(content, 'html', 'utf-8') email['Subject'] = subject email['From'] = sender email['To'] = to[0] msg = email.as_string() # Send email smtpObj.sendmail(sender, to, msg) smtpObj.quit() print('Email has been sent.')
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 as_binary_string(email): if PY3K: return email.as_bytes() else: return email.as_string()
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() print('Mail Sent')
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)