如何使用python发送短信形式的字符串+变量?

时间:2019-09-27 20:11:58

标签: python sms sms-gateway

程序运行完成后,我需要发送一条消息,但是我还想在程序中包含一些变量,例如程序在文本中运行的时间。

这是我发短信的代码:

import smtplib

carriers = {
    'att': '@mms.att.net',
    'tmobile': ' @tmomail.net',
    'verizon': '@vtext.com',
    'sprint': '@page.nextel.com'
}


def send(message):
    # Replace the number with your own, or consider using an argument\dict for multiple people.
    to_number = 'xxxxxxxxxx{}'.format(carriers['verizon'])
    auth = ('xxxxx', 'xxxx')

    # Establish a secure session with gmail's outgoing SMTP server using your gmail account
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(auth[0], auth[1])

    # Send text message through SMS gateway of destination number
    server.sendmail(auth[0], to_number, message)

很明显,我用xxx代替了我的信息。 现在,要发送我的文本,我要使用以下函数调用该函数:

found = 'The program is done!'
timetook = "Time took: %s (HOUR:MIN:SEC)" % timedelta(seconds=round(elapsed_time_secs))
send(found)
send(timetook)

它只是发送空白文本以显示时间,但是程序完成消息工作正常。如何发送时间记录?

1 个答案:

答案 0 :(得分:0)

问题是您没有遵循SMTP规则。下面是我多年前为自己编写的等效解决方案。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""SMS (short message service) functions."""

import logging
import smtplib
import sys
import rate_limiting

SMTP_GATEWAY = 'localhost'
FROM_ADDR = 'me@domain.us'
PHONE_NUMBER = '4081234567'
# T-Mobile SMS email gateway
# TO_ADDR = PHONE_NUMBER + '@tmomail.net'
# Verizon SMS email gateway
TO_ADDR = PHONE_NUMBER + '@vtext.com'

# Allow only three SMS messages per minute and five per hour.
short_term_rate_limiter = rate_limiting.SimpleRateLimiter(3, 60)
long_term_rate_limiter = rate_limiting.SimpleRateLimiter(5, 60 * 60)


def SendSms(msg, why=''):
    """Send a SMS message."""
    short_term_rate_exceeded = short_term_rate_limiter()
    long_term_rate_exceeded = long_term_rate_limiter()
    if short_term_rate_exceeded or long_term_rate_exceeded:
        logging.warning('SMS message rate exceeded, dropping msg: %s', msg)
        return

    smtp_conn = smtplib.SMTP(SMTP_GATEWAY)
    hdrs = 'From: {}\r\nTo: {}\r\n\r\n'.format(FROM_ADDR, TO_ADDR)
    if why:
        hdrs += 'Subject: {}\r\n'.format(why[:20])
    hdrs += "\r\n\r\n"
    max_msg_len = 140 - 3 - min(20, len(why))
    msg = hdrs + msg[:max_msg_len]
    # Make sure the message has only ASCII characters.
    msg = msg.encode('ascii', errors='replace').decode('ascii')
    smtp_conn.sendmail(FROM_ADDR, [TO_ADDR], msg)
    smtp_conn.quit()


if __name__ == '__main__':
    SendSms(' '.join(sys.argv[1:]))
相关问题