def job(): mail = GMail('*****@*****.**', 'Sgs123456') #mail = GMail('A.User <*****@*****.**>','password') html_content = """ <p style="text-align: center;">Cộng hòa xã hội chủ nghĩa Việt Nam</p> <p style="text-align: center;">Độc lập - Tự do - Hạnh phúc</p> <p style="text-align: center;"><strong>ĐƠN XIN NGHỈ HỌC</strong></p> <p style="text-align: left;">Kính gửi: Thầy</p> <p style="text-align: left;">Tên em là Minh.</p> <p style="text-align: left;">Hôm nay em xin nghỉ học vì {{ốm}}.</p> <p style="text-align: left;">Minh</p> """ sickness = ["đau bụng", "ẩy chỉa", "sốt xuất huyết"] reason = random.choice(sickness) html_content = html_content.replace("{{ốm}}", reason) message = Message("Test", "*****@*****.**", html=html_content) mail.send(message)
def contact(db): """ Our contact-us form, basically, present a form if it's a GET request, validate and process the form if it's a POST request. Filthy but works. """ form = ContactForm(request.POST, nocaptcha={'ip_address': '127.0.0.1'}) if request.method == 'POST' and form.validate(): # process the form, captcha is valid. message_text = "Contact Email: {email}\n\n {contact_text}".format( email=form.email.data, contact_text=form.contact_text.data) # put together a gmail client for sending messages gmail_client = GMail(settings.ADMIN_EMAIL, settings.ADMIN_EMAIL_PASSWORD) message = Message('[xqzes] Contact Form', to=settings.ADMIN_EMAIL, text=message_text) gmail_client.send(message) return redirect("/contact/?contacted=True") return template('contact', form=form, contacted=strtobool(request.GET.get('contacted', 'false')))
def job(): from gmail import GMail, Message import random gmail = GMail('*****@*****.**','techkids') symptom_dictionary = { 'đau bụng':'dạ dày', 'đau chân':'xương khớp', 'mệt mỏi':'ung thư', } html_template = ''' <p>Chào sếp</p> <p><strong>Sáng nay</strong> em {{ symptom }} quá. Chắc là em bị {{ disease }} rồi </p> <p><span style="color: #993366;">Cho em xin nghỉ ahuhu</span></p> <p> </p> ''' #get random symptom and disease symp_disease = [] symp_disease = random.choice(list(symptom_dictionary.items())) html_content = html_template.replace("{{ symptom }}",symp_disease[0]) html_content = html_content.replace("{{ disease }}",symp_disease[1]) msg = Message('This is Yen',to='*****@*****.**',html=html_content,attachments=[]) gmail.send(msg) return schedule.cancel_job
def sent_mail(x): gmail = GMail("*****@*****.**", "Theeternal0610") html_content = """Yêu cầu của bạn đã được xử lý, chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất. Cảm ơn bạn đã sử dụng dịch vụ của 'Mùa Đông Không Lạnh'""" msg = Message('Mùa Đông Không Lạnh', to=x, html=html_content) gmail.send(msg)
def test_gmail(self): gmail = GMail(os.environ["GMAIL_ACCOUNT"], os.environ["GMAIL_PASSWD"]) msg1 = Message("GMail Test Message #1", to=os.environ["GMAIL_RCPT"], text="Hello") msg2 = Message("GMail Test Message #2", to=os.environ["GMAIL_RCPT"], text="Hello") gmail.send(msg1) gmail.send(msg2) gmail.close()
def contact(db): """ Our contact-us form, basically, present a form if it's a GET request, validate and process the form if it's a POST request. Filthy but works. """ form = ContactForm(request.POST, nocaptcha={'ip_address': '127.0.0.1'}) if request.method == 'POST' and form.validate(): # process the form, captcha is valid. message_text = "Contact Email: {email}\n\n {contact_text}".format( email=form.email.data, contact_text=form.contact_text.data ) # put together a gmail client for sending messages gmail_client = GMail(settings.ADMIN_EMAIL, settings.ADMIN_EMAIL_PASSWORD) message = Message('[xqzes] Contact Form', to=settings.ADMIN_EMAIL, text=message_text) gmail_client.send(message) return redirect("/contact/?contacted=True") return template( 'contact', form=form, contacted=strtobool(request.GET.get('contacted', 'false')) )
def send_ebook(book, convert=False): print('sending %r' % book) gm = GMail(*settings.GMAIL_AUTH) m = Message("convert" if convert else "regular", to=settings.KINDLE_EMAIL, text="foo", attachments=[book]) gm.send(m)
def sent_mail_verify(x, y): gmail = GMail("*****@*****.**", "Theeternal0610") html_content = """ Cảm ơn bản đã sử dụng dịch vụ của chúng tôi Vui lòng click vào link dưới để xác nhận đăng ký tài khoản:{} Trân trọng cảm ơn!""".format(y) msg = Message('Xác nhận đăng ký tài khoản', to=x, html=html_content) gmail.send(msg)
def sent_mail(x, y): gmail = GMail("*****@*****.**", "Theeternal0610") html_content = """ Cảm ơn bản đã sử dụng dịch vụ của chúng tôi Mật khẩu mới của bạn là:{} Trân trọng cảm ơn!""".format(y) msg = Message('Khôi phục mật khẩu', to=x, html=html_content) gmail.send(msg)
def send_email(): # customer_id = Customer.objects().with_id(service_id) # packages = session['packages'] content = open('templates/mail.html', encoding="utf8").read() gmail = GMail('*****@*****.**', '123@123a') # msg = Message('Test Message',to = Customer[5], html = content) msg = Message("Test message", to=Customer[5], html=content) gmail.send(msg) return 'thank you'
def accept(order_id): order = Order.objects().with_id(order_id) order.update(set__is_accepted=True) order.reload() gmail = GMail('*****@*****.**', 'vukhanhduy') mess = "Yêu cầu của bạn đã được xử lý, chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất. Cảm ơn bạn đã sử dụng dịch vụ của ‘Mùa Đông Không Lạnh" msg = Message('Hello', to=order.email, html=mess) gmail.send(msg) return redirect(url_for('ordermanagement'))
def get_mailer(): with open('config.txt', 'r') as configfile: lines = [x for x in configfile] username = lines[0].rstrip().replace(' ', '') password = lines[1].rstrip().replace(' ', '') print 'connecting with ' + username + ' ' + password gmailer = GMail(username, password) gmailer.connect() return gmailer
def sendMail(): logger.info('Sending mail to %s', config['GMail']['to']) gmail = GMail(config['GMail']['username'],config['GMail']['password']) mail = Message(subject='New IP @ KA', to=config['GMail']['to'], sender='Automatic IP updater', text='Reported from: %s\nIP: %s' % (config['General']['hostname'],ip) ) gmail.send(mail) gmail.close()
def accept(id, id2): Order.objects.with_id(id).update(set__is_accepted=True) user = User.objects.with_id(id2) html_content = """ <p style="text-align: center;">“Yêu cầu của bạn đã được xử lý, chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất. Cảm ơn bạn đã sử dụng dịch vụ của ‘Mùa Đông Không Lạnh’”</p> """ gmail = GMail('*****@*****.**', 'english1996') msg = Message('TEST', to=user.email, html=html_content) gmail.send(msg) return "SUCCESSFULLY REQUEST"
def send_email(recipient=matt_email, msg='test'): try: gmail = GMail(maddie_email, app_password) msg1 = Message(f"Maddie's Math Results from {time}", to=recipient, text=msg) gmail.send(msg1) print("Message sent!") except Exception as e: print(f"Error sending email results. Error message: \n {e}")
def send_email(): bitcoin_price = get_bitcoin_price() # enter actual password, otherwise, nothing happens. gmail = GMail(f"{SENDER_TITLE} <{USERNAME}>", password=f'{PASSWORD}') message = Message(f'Bitcoin is at {bitcoin_price} right now!', to=RECIPIENT, text=f'The current Bitcoin price is {bitcoin_price}.') gmail.send(message)
def test_gmail(self): gmail = GMail(os.environ['GMAIL_ACCOUNT'], os.environ['GMAIL_PASSWD']) msg1 = Message('GMail Test Message #1', to=os.environ['GMAIL_RCPT'], text='Hello') msg2 = Message('GMail Test Message #2', to=os.environ['GMAIL_RCPT'], text='Hello') gmail.send(msg1) gmail.send(msg2) gmail.close()
def get_handler(email_address: str, api_key: str) -> GMail: """ Returns an EmailApp handler. :param email_address: :param api_key: :return: """ gmail_handler = GMail(username=email_address, password=api_key) gmail_handler.connect() return gmail_handler
def send_email(): report = generate_report() print(report) gmail = GMail('Storj Notification <{}>'.format(EMAIL_USERNAME), password=EMAIL_PASSWORD) message = Message("Daily Storj Report For Node {}".format(NODE_NICKNAME), to=EMAIL_SENDTO, text=report) gmail.send(message)
def order(order_id): all_order = Order.objects.with_id(order_id) service_id = all_order.service.id all_services = Service.objects.with_id(service_id) all_order.update(set__is_accepted=True) all_services.update(set__status=False) user_mail = all_order['user']['email'] html_content = ''' Yêu cầu của bạn đã được xử lý, chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất. Cảm ơn bạn đã sử dụng dịch vụ của "Mùa Đông Không Lạnh" ''' gmail = GMail('*****@*****.**', '01662518199') msg = Message('Mùa Đông Không Lạnh', to=user_mail, html=html_content) gmail.send(msg) return redirect(url_for('show_order'))
def send(self, person, information): gmail = GMail(env("GMAIL_USERNAME"), env("GMAIL_PASSWORD")) subject = "Fresh {info} {ip} !".format(info=information, ip=person["ip"]) to = env("EMAIL") body = self.prepareBody(person) message = Message(subject=subject, to=to, html=body) gmail.send(message)
def edit_order(order): f_order = Order.objects.with_id(order) f_order.update(set__is_accepted=True) gmail = GMail("*****@*****.**", "minimalism") html_content = """ <p> Yêu cầu của bạn đã được xử lý, chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất. Cảm ơn bạn đã sử dụng dịch vụ của ‘Mùa Đông Không Lạnh’</p> """ msg = Message('Xac nhan yeu cau', to=f_order.user_id.email, html=html_content) gmail.send(msg) return redirect(url_for('order_list'))
def verify_email(reveive_email, name, code): mail = GMail("smartexam.c4e22", "Sm@rt123456") body = ''' <div> <div>Dear {0},</div> <div>You have just signed up for Smart-Exam. Well done!</div> <div>Would you mind just validating that this is really your email address?</div> <div>Here is the verify code: {1}</div> <div>For additional help, please feel free to contact us via [email protected].</div> </div> '''.format(name, code) msg = Message("Smart-Exam confirmation email", to=reveive_email, html=body) mail.send(msg)
def accept(order_id): if "loggedin" in session: order = Order.objects.with_id(order_id) order.update(set__is_accepted=True) user = User.objects(account=order.service_user) for i in user: mail = i.email gmail = GMail('*****@*****.**', 'chung20150413') msg = Message('Test Message', to=mail, text='Hello') gmail.send(msg) all_order = Order.objects() return render_template('order.html', all_order=all_order) else: return redirect(url_for("login"))
def sign_up(): confirm_username = False confirm_email = False if request.method == "GET": return render_template("sign_up.html") elif request.method == "POST": form = request.form users = User.objects() for user in users: if form["email"] == user["email"]: confirm_email = True if form['username'] == user['username']: confirm_username = True if confirm_email: return "Email has been used. Try again" elif confirm_username: return "Username has been used. Try again" else: str_password = str(randint(1000, 9999)) new_user = User(fullname=form["fullname"], email=form["email"], username=form["username"], password=str_password) new_user.save() users = User.objects(username=form["username"]) from gmail import GMail, Message accept_account = """ <h1>Accept your Warm winter Account</h1> <h3><strong>Username: {{username}}</strong></h3> <h3>Password: {{password}}</h3> <p>" You can change your password in here :<a href="http://*****:*****@gmail.com', 'duchoa119') msg = Message('Accept Account', to=form['email'], html=accept_account) gmail.send(msg) return "Check your Email to Loggin"
def handleSCMessages(self, message): subject = GMail.getMessageSubjectFromMessage(message) if subject == "Transaction Alert Primary / Supplementary Card Email Alert": text = GMail.getMessageTextFromMessage(message) pattern = re.compile( r".*charging \+(.*) (\d+\.\d+) .* at (.*)\..*") result = pattern.findall(text) amount = None if len(result) > 0: return result[0] return (None, None, None)
def send_email(message): gmail = GMail( username = '******', password = '******' ) with open('friends.txt','r') as f: for friend in f: name = friend.split('s')[0].strip().title() email = friend.split(',')[1].strip() msg = Message(subject='***阳间天气预测资料***', sender=gmail.username, to=email, text=message) print('Sending email to {}'.format(name)) gmail.send(msg)
def send_email(recipient,sender,password,keyword,html,attachment=False): # enter actual password, otherwise, nothing happens. gmail = GMail('Alerts <'+sender+'>',password) if attachment: message = Message('Alerts for '+keyword, to=recipient, html=html, attachments=[attachment]) else: message = Message('Alerts for '+keyword, to=recipient, html=html) gmail.send(message)
def __init__(self, username: str, password: str, format: str = 'html', error_handler: Callable[[Recipient], None] = None, success_handler: Callable[[Recipient], None] = None, background: bool = True, parallel_threads: int = 1): self.username = username self.password = password self.gmail = GMail(self.username, self.password) self.error_handler = error_handler self.success_handler = success_handler self.background = background self.format = format self.is_connected = False
def send(): gmail = GMail('*****@*****.**', 'tuananh1k95') msg = Message('message', to='*****@*****.**', text="Hello world") gmail.send(msg) return "Sended"
def accepted(order_id): order = Order.objects.with_id(order_id) email = order.user.email # update field order.update( is_accepted = True ) # send email gmail = GMail("Minh<*****@*****.**>","someknownow") msg = Message( "Xét duyệt yêu cầu - Mùa Đông Không Lạnh", to=email, text="Yêu cầu của bạn đã được xử lý, chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất. Cảm ơn bạn đã sử dụng dịch vụ của ‘Mùa Đông Không Lạnh’") gmail.send(msg) return redirect(url_for("order"))
def send_mail(): user_object = Customers.objects.get(id=str(session["id"])) user_gmail = user_object['gmail'] gmail = GMail('*****@*****.**', 'thisishuyhieu') contentz = ''' <p>Đơn hàng của bạn đã được vận chuyển, cảm ơn bạn đã tin dùng dịch vụ của chúng tôi!!!</p> <p></p> <p>--Muadongkhonglanh-- </p>''' msg = Message('Muadongkhonglanh', to=user_gmail, html=contentz) # don_hang = Order.objects.get(id=) # order_items.update(set__is_accepted = "0") #2 dòng trên đang có vấn đề gmail.send(msg) return redirect(url_for('order_data'))
async def main(): logger = get_logger() logger.info("Start") auth = GAuth(logger) with open(f'{os.environ.get("SECRETS")}/creds.json', 'r') as f: creds = json.load(f) mail = GMail(auth.mail, logger) session = aiohttp.ClientSession() reports = Reports(session, mail, creds, logger) # Login login = asyncio.create_task(reports.login()) # Get events to process calendar = GCal(auth.calendar, creds["cal_id"], logger) calendar.query_calendar() # Make sure we're logged in & process events await login if len(calendar.users) > 0: # Call reports.dowload_reports_and_send_draft for each new event, this downloads report and creates draft done, pending = await asyncio.wait([ reports.download_reports_and_send_draft(data) for data in calendar.users ]) # Patch events that drafts were succesfully created for (returned +ve) for task in done: if result := task.result(): calendar.patch(result)
def main(): mail_config_path, db_config_path, profession_config_path, result_path, sleep_time, loop = get_parm(sys.argv[1:]) config = configparser.ConfigParser() arch = Archive(result_path + '/result_data.db') while True: config.read(mail_config_path) try: server = config['mail.config']['imap_server'] port = config['mail.config']['imap_port'] user = config['mail.config']['user'] password = config['mail.config']['password'] if config.has_option('mail.config', 'box'): box = config['mail.config']['box'] else: box = '' smtp_server = config['mail.config']['smtp_server'] smtp_port = config['mail.config']['smtp_port'] except KeyError as err: LOG.error('请检查邮件配置文件%s。\n%s', mail_config_path, str(err)) sys.exit(1) mail = GMail(server, port, user, password, box, smtp_server, smtp_port) LOG.debug('开始接收邮件') mail.parse() if len(mail.query_list) > 0: work = DOperating(dbconfig_path=db_config_path, proconfig_path=profession_config_path, result_save_path=result_path) while mail.query_list: query = mail.query_list.pop() result = work.query(parm=query) if result is None: LOG.info('邮件<%s>查询无结果', query['messageid']) else: LOG.info('查询成功%s', result) arch.add_data(query, result) mail.send_mail(query['from'], query['subject'].replace('[q]', '') + '结果', result) mail.delete(query['num']) LOG.debug('本次处理结束') mail.over() if not loop: break # 休眠指定时间 LOG.info('本次查询结束,休眠%s分钟', sleep_time) time.sleep(sleep_time * 60) arch.over()
def send_email(to_addr, subject, msg): mail = GMail(GMAIL_EMAIL, GMAIL_PASSWORD) mail.connect() if to_addr is list: to_addr = ', '.join(list(to_addr)) mail.send(Message(subject, to=to_addr, html=msg)) mail.close()
def cli(): import argparse, getpass, sys parser = argparse.ArgumentParser(description='Send email message via GMail account') parser.add_argument('--username', '-u', required=True, help='GMail Username') parser.add_argument('--password', '-p', default=None, help='GMail Password') parser.add_argument('--to', '-t', required=True, action='append', default=[], help='To (multiple allowed)') parser.add_argument('--cc', '-c', action='append', default=[], help='Cc (multiple allowed)') parser.add_argument('--subject', '-s', required=True, help='Subject') parser.add_argument('--body', '-b', help='Message Body (text)') parser.add_argument('--html', '-l', default=None, help='Message Body (html)') parser.add_argument('--attachment', '-a', action='append', default=[], help='Attachment (multiple allowed)') parser.add_argument('--debug', '-d', action='store_true', default=False, help='Debug') results = parser.parse_args() if results.password is None: results.password = getpass.getpass("Password:"******",".join(results.to), cc=",".join(results.cc), text=results.body, html=results.html, attachments=results.attachment) gmail.send(msg) gmail.close()
# Read credentials from options file parser = SafeConfigParser() parser.read('options.cfg') try: FROM = parser.get('Credentials', 'account') SECRET = parser.get('Credentials', 'password') TO = [parser.get('Configs', 'to')] MAX_MAILS = parser.getint('Configs', 'mails_amount') except Exception as e: print "Problem reading options.cfg" print "Exception: {0!r}".format(e) sys.exit() # create the GMail global object gmail = GMail(FROM, SECRET) directory = './emails/' file_list = [] for filename in os.listdir(directory): path = os.path.join(directory, filename) if os.path.isfile(path): file_list.append(path) print "Sending {0} mail(s)...".format(len(file_list)) for mail_file in file_list: print "Sending '{0}' ... ".format(mail_file), with open(mail_file) as f: email = f.read()
from gmail import GMail from gmail import Message from jinja2 import FileSystemLoader, Environment # targets = ['fonyou1337', 'inchiming', 'inbenming'] # for i in targets: gmail = GMail('ENsu <*****@*****.**>', 'XXXXXXXXXXXXXX') loader = FileSystemLoader(searchpath='./') Env = Environment(loader=loader) template = Env.get_template('./garbage.html') context = template.render({'receiver': 'ENsu'}) msg = Message('Garbage Message', to='ENsu <*****@*****.**>', text=context) gmail.send(msg)
while not setting(): 1 else: # When setting file exists, it is proof that initialization is done. conf = ConfigParser.SafeConfigParser() conf.read('iamhome.cfg') arptable.ping() # Chack whether MAC addr is in arp table and Send e-Mail. if arptable.check_devices(conf.get('General', 'MACAddr')): if not os.path.exists('.inhome.lock'): subject = unicode(conf.get('Message', 'Subject'), 'utf-8') body = unicode(conf.get('Message', 'Body'), 'utf-8') # Send e-mail and generate lock file inhome.lock # Lock file is checker of user in home gmail = GMail(conf.get('User', 'UserName'), conf.get('User', 'Password')) gmail.create_message(conf.get('General', 'Adressees'), subject, body) try: gmail.initialize_smtp() gmail.send_message() f = open('.inhome.lock', 'w') d = datetime.datetime.today() f.write(d.strftime("%Y-%m-%d %H:%M:%S")) f.close() print_with_current_time('Return Home!') except Exception as e: print_with_current_time('Cannot send a mail. Exit.',1) print >> sys.stderr, str(e) else: # User is in home # Do nothing
from jinja2 import Template from gmail import GMail, Message mailingList = {'Ins1':'*****@*****.**','Ins2':'*****@*****.**'} usr = GMail('*****@*****.**','xxxxx') template = Template('Hello {{ name }}!\nYour email is {{ email }}\nThis is a junk mail.\nHave a nice day.') for target in mailingList: context = template.render(name=target, email=mailingList[target]) msg = Message(to=mailingList[target],text=context,subject="Junk mail") print context usr.send(msg) usr.close()