Exemplo n.º 1
0
def send_message(number, mail, name, pass_no, parent_email, rector_contact,
                 message, sheet):
    # using twillio
    # #print("came here")
    # number2="+"+str(number)
    #
    # client = Client(messages.account_sid, messages.auth_token)
    # message = client.messages.create(
    #     to=number2,                                     # "+919876543210"
    #     from_="+14157920130",
    #     body=messages.message)
    # print("message successfully sent to,:",name)
    #
    sub = 'Notification from ISAC - Do Not Reply'
    student = requests.get(
        "http://api.msg91.com/api/sendhttp.php?sender=MSGIND&route=4&mobiles=+91"
        + str(number) +
        "&authkey=192990AkDQ3bDBv5a59de99&country=91&message=" + message)
    rector = requests.get(
        "http://api.msg91.com/api/sendhttp.php?sender=MSGIND&route=4&mobiles=+91"
        + str(rector_contact) +
        "&authkey=192990AkDQ3bDBv5a59de99&country=91&message=" +
        (messages.rector_sms % (name, pass_no)))
    print(messages.rector_sms % (name, pass_no))

    # Emailing
    gmail.send_message(mail, sub, message)
    gmail.send_message(parent_email, sub, message)

    row = [name, number, message, datetime.datetime.now().time()]
    sheet.append_row(row)
Exemplo n.º 2
0
def main(email_address, email_friendly_name, email_subject):
    """Writes the CSV data to the csv file, then opens a connection to gmail and sends the email with that attachment"""
    with open(FILENAME, 'w', newline='', encoding='utf-8-sig') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerows(CSV_DATA)

    service = gmail.setup()
    sender_email = email_address
    email_from = email_friendly_name + ' <' + sender_email +'>'

    for email in EMAILS:
        email_to = email
        message = gmail.create_message_with_attachment(email_from, email_to, email_subject, EMAIL_BODY, FILENAME)
        gmail.send_message(service, sender_email, message)
        time.sleep(0.5)
Exemplo n.º 3
0
def send_mail(key):
    if key == 'test':
        details = tmp_details
    else:
        details = user_details
    service = gmail.service_account_login()
    for user in details:
        user_name = user['name']
        user_email = user['email']
        msg_txt = format_data("kimoshare", user_name)

        message = gmail.create_message(EMAIL_FROM, user_email, EMAIL_SUBJECT,
                                       msg_txt)
        gmail.send_message(service, 'me', message)

    return True
Exemplo n.º 4
0
def sendEmail(contactInfo):

    SCOPES = [
        'https://www.googleapis.com/auth/gmail.readonly',
        'https://www.googleapis.com/auth/spreadsheets',
        "https://www.googleapis.com/auth/drive.file",
        "https://www.googleapis.com/auth/drive",
        "https://www.googleapis.com/auth/gmail.send"
    ]

    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "creds/serviceAccount.json"

    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('creds/token.pickle'):
        with open('creds/token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'creds/credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('creds/token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    # email each person in the contact list
    for person in contactInfo:
        email = person["emailAddress"]

        to = email
        sender = SENDER
        text = "WARNING: Dangerous levels of Carbon Monoxide have been detected"
        subject = "CO Level Warning"

        message1 = mail.create_message(sender, to, text, subject)

        mail.send_message(service, sender, message1)
Exemplo n.º 5
0
async def handler_edit_message(event):
    t = "N"
    if type(event) == events.MessageEdited.Event:
        t = "E"
    message = event.message
    chat = await client.get_entity(message.peer_id)
    chat_name = utils.get_display_name(chat)

    user_name = "me"
    if message.from_id:
        user = await client.get_entity(message.from_id)
        user_name = utils.get_display_name(user)

    logger.info(
        f'Get new message from user "{user_name}" in chat "{chat_name}"')

    tzinfo = timezone(timedelta(hours=Config.TIMEZONE))
    msg_dt = message.date.astimezone(tzinfo)
    subject = f'[{t}: {chat_name}:{user_name}][{msg_dt.strftime("%d.%m %H:%M:%S")}]'
    send_message(message.message, subject)
Exemplo n.º 6
0
def handle(event, context):
    """
    Lambda handler
    """
    taaze = Taaze()
    taaze_rows = taaze.sql.query(TableTaaze)\
        .filter(TableTaaze.active == True)\
        .all()
    taaze.login()
    for row in taaze_rows:
        res = taaze.query(row.isbn)
        # print(json.dumps(res, indent=4, ensure_ascii=False, cls=JSONEncoder))
        logger.info(json.dumps(res, indent=4,
                               ensure_ascii=False, cls=JSONEncoder))
        if not row.title and res['title']:
            row.title = res['title']
        if not row.pub and res['pub']:
            row.pub = res['pub']
        if res['flag'] == 'B':
            row.active = False
            row.message = res['message']
        time.sleep(1)
    # print("売れる:{}".format(len(taaze.result)))
    logger.info("売れる:{}".format(len(taaze.result)))
    if taaze.result:
        subject = "{}件売れるやつがあった".format(len(taaze.result))
        # print(json.dumps(taaze.result, indent=4,
        #                  ensure_ascii=False, cls=JSONEncoder))
        logger.info(json.dumps(taaze.result, indent=4,
                               ensure_ascii=False, cls=JSONEncoder))
    else:
        subject = "売れるやつが無かった"

    body = json.dumps(taaze.result, indent=4,
                      ensure_ascii=False, cls=JSONEncoder)
    msg = create_message(GMAIL_ADDR, RECEIVE_ADDR, subject, body)
    send_message(GMAIL_ADDR, [RECEIVE_ADDR], msg)
    taaze.sql.commit()
    taaze.sql.close()
Exemplo n.º 7
0
import gmail

gmail.send_message('*****@*****.**', 'Test from PU Email',
                   'This is to test PU Email Id from Python. - Vatsal.')
gmail.send_message('*****@*****.**', 'Test from PU Email',
                   'This is to test PU Email Id from Python. - Vatsal.')
Exemplo n.º 8
0
        raise Exception("unknown option: " + x)

    allBadUIDs = []

    if checkInbox:
        try:
            mailHoursBack, allBadUIDs = findOldestInInbox()
            if mailHoursBack > hoursBack:
                hoursBack = mailHoursBack
        except Exception, e:
            print("couldn't check inbox: " + str(e))

    text = getText()

    if text == "":
        sys.exit(0)

    if sendEmail:
        import mypwd
        gmail.send_message("*****@*****.**",
                           "jira summary @ %s @ %s" %
                           (hoursBack, str(datetime.datetime.utcnow())),
                           text,
                           smtpPass=mypwd.pwd,
                           smtpNiceName="Eliot Jira Bot")

        if len(allBadUIDs) > 0:
            archiveOldMail(allBadUIDs)
    else:
        print(text)
Exemplo n.º 9
0
def send_basic_mail(content: str, to: List[str], obj: str):
    templates = parse_mail_template(content, to, obj, as_message=True)

    for t in templates:
        # Send the mails
        send_message(GMAIL_SERVICE, "me", t)
Exemplo n.º 10
0
def send_alert(message_text, subject):
    for to in mail_to:
        message = create_message(mail_from, to, subject, message_text)
        send_message("me", message)
Exemplo n.º 11
0
def main():
    with open("report.html", "r") as report_file, open("recipients.csv", "r") as recipients_file:
        recipients = recipients_file.read().split(',')
        email =  send_message("*****@*****.**",recipients, "End of shift report", report_file.read(), 'html')
        print("Email Sent.")
        print(email)
Exemplo n.º 12
0
def email_pairs(pairings_dir: str,
                pairing_num: int,
                sender_name: str,
                my_email: str = None,
                subject_prefix: str = 'Pairing',
                token_path: str = 'token.pickle',
                credentials_path: str = 'credentials.json') -> None:
    """
    Emails each pair of people in a pairing.

    :param pairings_dir: Path to a directory where the random pairings are saved.
    :param pairing_num: The number of the pairing to send.
    :param sender_name: The name of the sender, which is the name signed at the bottom of the email.
    :param my_email: The email of the sender if the sender is a participant in the pairing.
    :param subject_prefix: The prefix used in the subject header, followed by pairing_num.
    :param token_path: Path to user token .pickle file. If it doesn't already exist,
                       it will be saved here.
    :param credentials_path: Path to credentials .json file.
    """
    # Load pairing
    pairing = pd.read_csv(
        os.path.join(pairings_dir, f'pairing_{pairing_num}.csv'))

    # Convert NaN to None
    pairing = pairing.where(pairing.notna(), None)

    # Create subject
    subject = f'{subject_prefix.strip()} {pairing_num}'

    # Build email messages
    messages = []
    for name_1, email_1, name_2, email_2 in pairing.itertuples(index=False):
        # Check names and emails are None at the same time
        if (name_1 is None) != (email_1 is
                                None) or (name_2 is None) != (email_2 is None):
            raise ValueError('Names and emails are not None at the same time.')

        # If both are None, continue
        if name_1 is None and name_2 is None:
            continue

        # If one is None, create unpaired message
        elif name_1 is None or name_2 is None:
            name = name_1 if name_1 is not None else name_2
            to = email_1 if email_1 is not None else email_2
            message_text = (
                f'Hi {name},\n'
                f'\n'
                f'Unfortunately you don\'t have a partner this week. '
                f'But don\'t worry, you\'ll have a partner again next week!\n'
                f'\n'
                f'Best,\n'
                f'{sender_name}')

        # If neither is none and one is me, send special paired message
        elif email_1 == my_email or email_2 == my_email:
            name, to = (name_1, email_1) if email_1 != my_email else (name_2,
                                                                      email_2)
            message_text = (f'Hi {name},\n'
                            f'\n'
                            f'You\'re paired with me this week! '
                            f'When would be a good time to chat?\n'
                            f'\n'
                            f'Best,\n'
                            f'{sender_name}')

        # If neither is none and neither is me, send paired message
        else:
            to = f'{email_1},{email_2}'
            message_text = (
                f'Hi {name_1} and {name_2},\n'
                f'\n'
                f'You two are paired this week! '
                f'Please try to find a time by the end of the week to chat.\n'
                f'\n'
                f'Best,\n'
                f'{sender_name}')

        print(f'Email {len(messages) + 1}\n'
              f'To: {to}\n'
              f'Subject: {subject}\n\n'
              f'{message_text}\n')

        messages.append(
            create_message(to=to, subject=subject, message_text=message_text))

    # Check whether to send the emails
    if input(f'Would you like to send these {len(messages):,} emails? Y/n: '
             ).lower() != 'y':
        print('Not sending emails')
        return

    # Load Gmail service
    print('Building Gmail service')
    service = build_service(token_path=token_path,
                            credentials_path=credentials_path)

    # Send emails
    print('Sending emails')
    for i, message in enumerate(messages):
        message = send_message(service=service, message=message)
        print(f'Message {i} Id: {message["id"]}')
Exemplo n.º 13
0
import requests
from gmail import send_message
import os.path

with open("polls-initial.json") as f:
    saved_polls = json.load(f)

saved_president = [x for x in saved_polls if x["type"] == "president-general"]

URL = "https://projects.fivethirtyeight.com/polls/polls-initial.json"
r = requests.get(URL)
r.raise_for_status()
polls = r.json()
president = [x for x in polls if x["type"] == "president-general"]

# no timestamp, only ids and ordering
max_id = max([x["id"] for x in president])
max_saved_id = max([x["id"] for x in saved_president])

new_poll_found = max_id != max_saved_id

if new_poll_found:
    print("sending email...")
    send_message()
    print("email sent")
    with open("polls-initial.json", "wb") as f:
        f.write(r.content)
        print("saving new polls-initial.json")
else:
    print("No new polls found.")
Exemplo n.º 14
0
def send_email(first_name, email_id, route_string):
    subject = "This is Emailing TEST. Do not respond to BOT. #ByVatsal"
    bodyHTML = 'Hey there, <br><br>Howdy %s ? I am FeedBot. I request you to please fill the feedback form by clicking <a href="http://134.209.42.61/chatbot/%s">here</a>.<br><br>It would not take much time.<br><br><br><a href="https://codingprivacy.github.io">CodingPrivacy.</a>' %(first_name, route_string)
    gmail.send_message(email_id, subject, bodyHTML)
    _logs.save_logs(email_id, route_string)
Exemplo n.º 15
0
    allBadUIDs = []

    if checkInbox:
        try:
            mailHoursBack,allBadUIDs = findOldestInInbox()
            if mailHoursBack > hoursBack:
                hoursBack = mailHoursBack
        except Exception,e:
            print( "couldn't check inbox: " + str(e) )

    text = getText()

    if text == "":
        sys.exit(0)

    if sendEmail:
        import mypwd
        gmail.send_message( "*****@*****.**",
                            "jira summary @ %s @ %s" % ( hoursBack,  str(datetime.datetime.utcnow() ) ),
                            text,
                            smtpPass=mypwd.pwd,
                            smtpNiceName="Eliot Jira Bot")

        if len(allBadUIDs) > 0:
            archiveOldMail( allBadUIDs )
    else:
        print( text )