简体   繁体   English

使用 Python 发送具有不同正文的邮件的正确方法

[英]Proper way to send mail with different body using Python

I'm wondering which approach is better for sending mail with different body using Python:我想知道哪种方法更适合使用 Python 发送不同正文的邮件:

  • send each mail using separate functions使用单独的函数发送每封邮件
  • using one function and select body message with if-else statement使用带有 if-else 语句的 function 和 select 正文消息

First case:第一种情况:

FROM = *from_email_address*

def send_mail_notify():

    SUBJECT = *some_subject_for_notification_event*
    TEXT = *any_text*

    msg = EmailMessage()
    msg['From'] = FROM
    msg['To'] = *to_email_address*
    msg['Subject'] = SUBJECT
    msg.set_content(TEXT)
    
    ...(initialize connection to mail server, etc.)
FROM = *from_email_address*

def send_mail_error():

    SUBJECT = *some_subject_for_error_event*
    TEXT = *any_text*

    msg = EmailMessage()
    msg['From'] = FROM
    msg['To'] = *email_address*
    msg['Subject'] = SUBJECT
    msg.set_content(TEXT)
    
    ...(initialize connection to mail server, etc.)

Second case:第二种情况:

FROM = *from_email_address*

def send_mail(param):

    if param == "notify":
        SUBJECT = *some_subject_for_notification_event*
        TEXT = *any_text*
    elif param == "error":
        SUBJECT = *some_subject_for_error_event*
        TEXT = *any_text*

    msg = EmailMessage()
    msg['From'] = FROM
    msg['To'] = *email_address*
    msg['Subject'] = SUBJECT
    msg.set_content(TEXT)

   ...(initialize connection to mail server, etc.)

You can create an unlimited functions for different types of subject and text and you don't need to check the condition with if-else statement:您可以为不同类型的subjecttext创建无限的功能,您无需使用 if-else 语句检查条件:

FROM = *from_email_address*

def notify():
    return {"SUBJECT":"notification", "TEXT": "new message"}

def error():
    return {"SUBJECT":"error: message dont send", "TEXT": "error message text"}

def send_mail(param):
    msg = EmailMessage()
    msg['From'] = FROM
    msg['To'] = *email_address *
    msg['Subject'] = globals().get(param)()["SUBJECT"]
    msg.set_content(globals().get(param)()["TEXT"])

The param value must be the same as the name of the function . param值必须与function的名称相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM