【问题标题】:Can we use a user defined function with some parameters, multiple times in a python program?我们可以在python程序中多次使用带有一些参数的用户定义函数吗?
【发布时间】:2020-12-30 05:53:37
【问题描述】:

我想在我的 python 程序中为不同的情况发送邮件,但是我的“消息”(检查程序)在每种情况下都是不同的,我该如何解决这个问题? 我想每次使用相同的用户定义函数发送不同消息的邮件,即sendmail(mail,message)

def sendmail(mail,message):
    port = 587  # For starttls
    smtp_server = "smtp.gmail.com"
    sender_email = "something@gmail.com"
    receiver_email = mail
    password = 'password123'

    context = ssl.create_default_context()
    with smtplib.SMTP(smtp_server, port) as server:
        server.ehlo()  # Can be omitted
        server.starttls(context=context)
        server.ehlo()  # Can be omitted
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message)

message = f"""\         #my first message
  Subject: Use OTP {no} Dear {extname(am1)}, 
  Use OTP {no} to access your account. 
  Don't share it with someone else. """ 
  sendmail(mail,message) 

  message = f'''\         #my second message
  Subject: ZABANK: Current Balance 
  Dear {extname(am1)}, 
  Your current balance is {extbal(am1)} rupees. ''' 
  sendmail(mail,message) 

我最终收到了两次我的第一条消息。 在这里,mail 不是必需的,因为它是分配给另一个用户定义函数的变量。

【问题讨论】:

  • 向我们展示您调用 sendmail 的代码
  • 您可以使用列表来存储您的消息
  • 你说“我想用同一个用户定义函数,即sendmail(mail,message”,每次发送不同消息的邮件。多次调用用户定义函数,每次都通过第二个参数(消息)的不同值。
  • @Martheen 这是问题本身。
  • 多次调用自定义函数有困难吗(每次第二个参数都不一样)?

标签: python function ssl user-defined-functions


【解决方案1】:

您不能调用该功能两次,因为它需要同时进行两次 SMTP 登录, 即在您已登录时登录您的帐户(因此未发送第二条消息)。你可以通过遍历你的消息列表来克服这个问题

#please change your funtion name to avoid collision with the smtp.SMTP.sendmail method 
def usersendmail(mail,message):
    port = 587  # For starttls
    smtp_server = "smtp.gmail.com"
    sender_email = "something@gmail.com"
    receiver_email = mail
    password = 'password123'

    context = ssl.create_default_context()
    with smtplib.SMTP(smtp_server, port) as server:
        server.ehlo()  # Can be omitted
        server.starttls(context=context)
        server.ehlo()  # Can be omitted
        server.login(sender_email, password)
        for msg in messagelist:
            server.sendmail(sender_email, receiver_email, msg)

usersendmail("them@gmail.com",["mymessage1","mymessage2"])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2021-03-15
    相关资源
    最近更新 更多