def sendmail(mailto, subject, html='', text='', textfile='', htmlfile='', attachments=''): '''send mail''' if not mailto: print 'Error: Empty mailto address.\n' return mailto = [sb.strip() for sb in mailto.split(',')] if attachments: attachments = [att.strip() for att in attachments.split(',')] else: attachments = [] message = Message(From=USERNAME, To=mailto, Subject=subject) message.Body = text message.Html = html message.charset = 'utf8' try: if htmlfile: message.Html += open(htmlfile, 'r').read() if textfile: message.Body += open(textfile, 'r').read() except IOError: pass for att in attachments: message.attach(att) sender = Mailer(SERVER) sender.login(USERNAME, PASSWD) sender.send(message)
def sendMail(item, hwp): sender = Mailer('smtp.gmail.com', use_tls=True) for to in MAILER_TO: sender.login(MAILER_USERNAME, MAILER_PASSWORD) message = Message(From='*****@*****.**', To=to) message.Subject = "가정통신문 :%s" % item['title'].encode('utf-8') message.Html = "" if hwp: message.attach(hwp) sender.send(message)
def sendMail(item, hwp): sender = Mailer('smtp.gmail.com',use_tls=True) for to in MAILER_TO : sender.login(MAILER_USERNAME,MAILER_PASSWORD) message = Message(From='*****@*****.**', To=to) message.Subject = "가정통신문 :%s"%item['title'].encode('utf-8') message.Html = "" if hwp: message.attach(hwp) sender.send(message)
def send_email(from_email, to_email_list, subject, html, smtp_host, smtp_port=587, username=None, password=None): message = Message(From=from_email, To=to_email_list, charset='utf-8') # Keep from creating threads in gmail... message.Subject = "{} -- {}".format(subject, datetime.now().strftime('%Y-%m-%dT%H:%M:%S')) message.Html = html.encode('utf-8') message.Body = 'See the HTML!' sender = Mailer(host=smtp_host, port=smtp_port, use_tls=True, usr=username, pwd=password) if username is not None: sender.login(username, password) sender.send(message)
def send_email(self): """Envia el correo""" sender = Mailer("smtp.gmail.com", 587, True) sender.login("*****@*****.**", "90062957564") try: sender.send(self.message) except smtplib.AMTPAuthenticationError as Error: print(Error) return False except IOError as (error_string, error_number): print(str(error_string) + " " + str(error_number)) return False
def sendVerificationMail(user, address, code): # send message message = Message(From="\"Galaxy Harvester Activation\" <{0}>".format( mailInfo.REGMAIL_USER), To=address) message.Subject = "Galaxy Harvester Account Verification" link = "http://galaxyharvester.net/verifyUser.py?vc={0}".format(code) message.Body = "Hello " + user + ",\n\nYou have created a new account on galaxyharvester.net using this email address. Before you can use your new account, you must verify this email with us by clicking the link below. If the link does not work, please copy the link and paste it into your browser address box.\n\n" + link + "\n\nThanks,\n-Galaxy Harvester Administrator\n" message.Html = "<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>Hello " + user + ",</p><br/><p>You have created a new account on galaxyharvester.net using this email address. Before you can use your new account, you must verify this email with us by clicking the link below. If the link does not work, please copy the link and paste it into your browser address box.</p><p><a style='text-decoration:none;' href='" + link + "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>Click Here To Verify</div></a><br/>or copy and paste link: " + link + "</p><br/><p>Thanks,</p><p>-Galaxy Harvester Administrator</p>" mailer = Mailer(mailInfo.MAIL_HOST) mailer.login(mailInfo.REGMAIL_USER, mailInfo.MAIL_PASS) mailer.send(message) return 'email sent'
def sendGalaxyNotifyMail(galaxyID, galaxyName, user): # send message message = Message( From="\"Galaxy Harvester Registration\" <*****@*****.**>", To="*****@*****.**") message.Subject = "New Galaxy Submitted For Review" link = "http://galaxyharvester.net/galaxy.py/{0}".format(galaxyID) message.Body = user + " has submitted a new galaxy for review.\n\n" + link message.Html = "<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>" + user + " has submitted a new galaxy for review.</p><p><a style='text-decoration:none;' href='" + link + "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>Click Here To Review</div></a><br/>or copy and paste link: " + link + "</p>" mailer = Mailer(mailInfo.MAIL_HOST) mailer.login(mailInfo.MAIL_USER, mailInfo.MAIL_PASS) mailer.send(message) return 'email sent'
def sendAlertMail(conn, userID, msgText, link, alertID, alertTitle): # Don't try to send mail if we exceeded quota within last hour lastFailureTime = datetime(2000, 1, 1, 12) currentTime = datetime.fromtimestamp(time.time()) timeSinceFailure = currentTime - lastFailureTime try: f = open("last_email_failure.txt") lastFailureTime = datetime.strptime(f.read().strip(), "%Y-%m-%d %H:%M:%S") f.close() timeSinceFailure = currentTime - lastFailureTime except IOError as e: sys.stdout.write("No last failure time\n") if timeSinceFailure.days < 1 and timeSinceFailure.seconds < 3660: return 1 # look up the user email cursor = conn.cursor() cursor.execute("SELECT emailAddress FROM tUsers WHERE userID='" + userID + "';") row = cursor.fetchone() if row == None: result = "bad username" else: email = row[0] if (email.find("@") > -1): # send message message = Message(From="\"Galaxy Harvester Alerts\" <*****@*****.**>",To=email) message.Subject = "".join(("Galaxy Harvester ", alertTitle)) message.Body = "".join(("Hello ", userID, ",\n\n", msgText, "\n\n", link, "\n\n You can manage your alerts at http://galaxyharvester.net/myAlerts.py\n")) message.Html = "".join(("<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>Hello ", userID, ",</p><br/><p>", msgText.replace("\n", "<br/>"), "</p><p><a style='text-decoration:none;' href='", link, "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>View in Galaxy Harvester</div></a><br/>or copy and paste link: ", link, "</p><br/><p>You can manage your alerts at <a href='http://galaxyharvester.net/myAlerts.py'>http://galaxyharvester.net/myAlerts.py</a></p><p>-Galaxy Harvester Administrator</p>")) mailer = Mailer(mailInfo.MAIL_HOST) mailer.login(mailInfo.ALERTMAIL_USER, mailInfo.MAIL_PASS) try: mailer.send(message) result = 'email sent' except SMTPRecipientsRefused as e: result = 'email failed' sys.stderr.write('Email failed - ' + str(e)) trackEmailFailure(datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")) # update alert status if ( result == 'email sent' ): cursor.execute('UPDATE tAlerts SET alertStatus=1, statusChanged=NOW() WHERE alertID=' + str(alertID) + ';') else: result = 'Invalid email.' cursor.close()
def sendVerificationMail(user, address, code): # send message message = Message( From= "\"Galaxy Harvester Registration\" <*****@*****.**>", To=address) message.Subject = "Galaxy Harvester Email Change Verification" link = "http://galaxyharvester.net/verifyUser.py?vc={0}&vt=mail".format( code) message.Body = "Hello " + user + ",\n\nYou have updated your e-mail address on galaxyharvester.net to this email address. You must verify this email with us by clicking the link below before the change can be completed. If the link does not work, please copy the link and paste it into your browser address box.\n\n" + link + "\n\nThanks,\n-Galaxy Harvester Administrator\n" message.Html = "<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>Hello " + user + ",</p><br/><p>You have updated your e-mail address on galaxyharvester.net to this email address. You must verify this email with us by clicking the link below before the change can be completed. If the link does not work, please copy the link and paste it into your browser address box.</p><p><a style='text-decoration:none;' href='" + link + "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>Click Here To Verify</div></a><br/>or copy and paste link: " + link + "</p><br/><p>Thanks,</p><p>-Galaxy Harvester Administrator</p>" mailer = Mailer(mailInfo.MAIL_HOST) mailer.login(mailInfo.REGMAIL_USER, mailInfo.MAIL_PASS) try: mailer.send(message) except SMTPRecipientsRefused: return 'email not valid' return 'email sent'
class Sender(object): """Communication engine""" def __init__(self, config): """ Loads configuration, and logs in with twitter and mailer :config: configuration array """ self._config = config self.twitter = Twitter(auth=OAuth( self._config['twitter']['oauth'][0], self._config['twitter']['oauth'][1], self._config['twitter']['oauth'][2], self._config['twitter']['oauth'][3] )) self.sender = Mailer('smtp.gmail.com', use_tls=True, port=587) self.sender.login(self._config['mail']['address'], self._config['mail']['pass']) def send_mail(self, html): """ Send a mail via smtps """ message = Message( From=self._config['mail']['address'], To=self._config['mail']['to'], Subject=self._config['mail']['subject'] ) message.Html = html return self.sender.send(message) def publish_twitter(event, event_url): """ Simple twitter status update with the event url and title """ return self.twitter.statuses.update(status='%s: %s' %(event, event_url))
def enviar_email(mensagem, emails_destino, remetente, servidor, porta, usuario, senha, extra): message = Message(From=remetente, To=emails_destino, charset="utf-8") if extra: message.Subject = "DouFinder - EDIÇÃO EXTRA" else: message.Subject = "DouFinder" message.Body = mensagem try: sender = Mailer(servidor, port=porta) if usuario and senha: sender.login(usuario, senha) sender.send(message) except smtplib.SMTPRecipientsRefused as e: print("ERRO AO ENVIAR LOG: %s" % str(e.recipients)) except smtplib.SMTPException as e: print("ERRO AO ENVIAR LOG: %s" % e) except smtplib.SMTPAuthenticationError as e: print("ERRO AO ENVIAR LOG: %s" % e)
def mail_admins(subject, message, fail_silently=False): """Send a message to the admins in conf.ADMINS.""" from celery import conf if not conf.ADMINS: return to = ", ".join(admin_email for _, admin_email in conf.ADMINS) username = conf.EMAIL_HOST_USER password = conf.EMAIL_HOST_PASSWORD message = Message(From=conf.SERVER_EMAIL, To=to, Subject=subject, Body=message) try: mailer = Mailer(conf.EMAIL_HOST, conf.EMAIL_PORT) username and mailer.login(username, password) mailer.send(message) except Exception: if not fail_silently: raise
import premailer template = premailer.transform(template) # Clean HTML import lxml.html from lxml.html.clean import Cleaner cleaner = Cleaner() cleaner.kill_tags = ['style', 'script'] page = cleaner.clean_html(lxml.html.fromstring(template)) assert not page.xpath('//style'), 'style' assert not page.xpath('//script'), 'script' template = lxml.html.tostring(page).decode('utf-8') # Send mails sender = Mailer('smtp.yandex.com.tr', port='465', use_ssl=True) sender.login(config.user_mail, getpass('Password: '******'start') for receiver_name, receiver_mail in receivers: try: message = Message(From=config.user_mail, To=receiver_mail, charset="utf-8") attachment_path = glob( os.path.join(config.attachments_path, receiver_name + '.*'))[0] message.Subject = config.subject message.Html = template.format(NAME=receiver_name) message.attach(attachment_path) sender.send(message) except Exception as ex: print(receiver_name, receiver_mail, 'Failed\n', ex) print('Done')
class EmailSender: def __init__(self, *, buffer_size=5): self.mailer = Mailer('smtp.gmail.com', 587, use_tls=True) self.mailer.login(usr="******", pwd="#Rguih1m37x") self.flats_buffer = [] self.buffer_size = buffer_size @staticmethod def _display_to_html(flat_dict, root): address_attr = flat_dict['attributes'].get("Lokalizacja", "") gmaps_attr = flat_dict['address'] extracted_addr = [ addr for addr in flat_dict['description_extracted_attributes'] ['address'].values() ] table = ET.SubElement( root, "table", style="border: 1px solid black; background-color: #E9967A") for label, value in [ ('title', flat_dict['title']), ('price', flat_dict['price']), ('address_attr', address_attr), ('gmaps_attr', gmaps_attr), ('extracted_addr', extracted_addr), ('gmaps_attr', gmaps_attr), ('description', flat_dict['description']), ('link', flat_dict['url']), ]: label = str(label) value = str(value) tr = ET.SubElement(table, "tr") ET.SubElement(tr, "td").text = label ET.SubElement(tr, "td").text = value for photo in flat_dict['photos']: tr = ET.SubElement(table, "tr") ET.SubElement(tr, "img", src=photo) # SEPARATORS ET.SubElement(root, "hr") ET.SubElement(root, "br") ET.SubElement(root, "br") ET.SubElement(root, "hr") def flush(self): root = ET.Element("html") for flat in self.flats_buffer: flat_dict = flat.to_dict() self._display_to_html(flat_dict, root) message = Message(From="*****@*****.**", To="*****@*****.**") message.Subject = f"MIESZKANIA" message.Html = ET.tostring(root, method='html') self.mailer.send(message) def send(self, flat): self.flats_buffer.append(flat) if len(self.flats_buffer) >= self.buffer_size: self.flush() self.flats_buffer.clear() def __del__(self): self.flush()
app = Flask(__name__) app.config.from_object('configuration') pwd = os.environ.get("SQL_PASS") databaseConnection = DatabaseConnection("127.0.0.1", "root", pwd, "mydb") # Mail setup username = "******" password = "******" sender = Mailer("smtp.gmail.com", usr=username, pwd=password, port=465, use_ssl=True) sender.login(username, password) def sendVerifyEmail(email): message = Message(From=username, To=email, charset="utf-8") message.Subject = "Verify email" message.Html = "<a href='http://10.14.180.244:5000/verifyemail?email=" + email + "'" + ">Verify email</a>" sender.send(message) print("Sent verification") @app.route('/', methods=["GET", "POST"]) def index(): if request.method == "POST": email = request.form.get("email") maxEmails = request.form.get("maxNo")
work = Queue.Queue() i = 0 for x in data: if i is 0: pass i = i + 1 else: work.put(x) totalsent = work.qsize() print totalsent threads = [] for i in range(2): thread = threading.Thread(target=sendsend) thread.start() threads.append(thread) print "Waiting" for thread in threads: thread.join() print "Done" message = Message(From="Jarvis", To=["*****@*****.**"], Subject="Price Comparison") message.Body = "Message sent to " + str(totalsent) + " customers" sender = Mailer('smtp.gmail.com',port=587,use_tls=True) sender.login("*****@*****.**","coldplay@123") sender.send(message)
self.birthdays = [ Birthday(event) for event in search_birthdays(calendar=calendar, days=days) ] logging.info("Connecting to caldav calendar") client = caldav.DAVClient(calendar_url) principal = client.principal() calendars = principal.calendars() if len(calendars) > 0: calendar = calendars[0] else: logging.error("No calendar found") sys.exit(1) reports = [ Report(calendar, days=7), Report(calendar, days=30) ] env = Environment(loader=FileSystemLoader('templates'), autoescape=select_autoescape(['html', 'xml'])) template = env.get_template('email_notification.html') email_body_html = template.render(reports=reports) message = Message(From=os.environ.get('EMAIL_FROM'), To=[os.environ.get('EMAIL_TO')], charset="utf-8") message.Subject = "Rappel anniversaires !" message.Html = email_body_html message.Body = """This is alternate text.""" sender = Mailer(os.environ.get('SMTP_HOST'), port=os.environ.get('SMTP_PORT'), use_tls=False, use_ssl=True) sender.login(os.environ.get('SMTP_USER'),os.environ.get('SMTP_PASS')) sender.send(message)