Send an email with a Function Compute node

更新时间:
复制 MD 格式

This article describes how to use a DataWorks Function Compute node in DataWorks to call the Function Compute service to send emails.

Prerequisites

Limitations

The Function Compute feature is available only in workspaces that reside in the following regions: China (Hangzhou), China (Shanghai), China (Beijing), China (Zhangjiakou), China (Shenzhen), China (Chengdu), China (Hong Kong), Singapore, Malaysia (Kuala Lumpur), Indonesia (Jakarta), Germany (Frankfurt), UK (London), US (Silicon Valley), and US (Virginia).

Step 1: Create an event function

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions. In the top navigation bar, select the target region. On the Functions page, click Create Function.

  2. Select Event Function and click Create Event Function. In the Function Code section, set Runtime to built-in runtime > Python > Python 3.10 and set Code Upload Method to Use sample code. Then, click Create.

    For more information about function configuration, see Create an event function.

  3. On the function details page, on the Code tab, edit the index.py file and enter the following sample code for sending an email:

    Important
    • In the sample code, replace the values of the mail_host, mail_port, mail_username, mail_password, mail_sender, and mail_receivers parameters with their actual values.

    • The SMTP service must be enabled for your email account. Some email service providers do not enable this service by default. You need to check and enable it manually. For example, the SMTP service is disabled by default for 163 Mail accounts.

    • For security reasons, some email service providers may require a dedicated authorization code instead of your account password for third-party email clients to log in. In this case, set the mail_password parameter to the authorization code, not the account password. For example, 163 Mail uses an authorization code that must be used as the password for third-party logins.

    # -*- coding: utf-8 -*-
    import logging
    import json
    import smtplib
    from email.mime.text import MIMEText
    
    def handler(event, context):
      evts = json.loads(event)
    
      logger = logging.getLogger()
      logger.info('event: %s', evts)
      mail_host = 'smtp.163.com'                 ## Email server address
      mail_port = '465';                         ## SMTP port number
      mail_username = 'sender_****@163.com'      ## Login username
      mail_password = 'EWEL******KRU'            ## Login password
      mail_sender = 'sender_****@163.com'        ## Sender email address
      mail_receivers = ['receiver_****@163.com'] ## Recipient email address
    
      mail_content=generate_mail_content(evts)
      message = MIMEText(mail_content,'plain','utf-8')
      message['Subject'] = 'mail test'
      message['From'] = mail_sender
      message['To'] = mail_receivers[0]
      smtpObj = smtplib.SMTP_SSL(mail_host + ':' + mail_port)
      smtpObj.login(mail_username,mail_password)
      smtpObj.sendmail(mail_sender,mail_receivers,message.as_string())
      smtpObj.quit()
      return 'mail send success'
    
    def generate_mail_content(evt):
      mail_content=''
      if 'msg' in evt.keys():
          mail_content=evt['msg']
      else:
          logger = logging.getLogger()
          logger.error('msg not present in event')
      '''
      You can add logic here to process the email content.
      '''
      return mail_content
  4. Click Deploy Code.

Step 2: (Optional) Test the function

You can simulate a test by configuring the parameters for Create New Test Event.

  1. On the function details page, on the Code tab, click the image.png icon to the right of Test Function and select Configure Test Parameters from the drop-down list.

    In the Configure Test Parameters panel, select Create New Test Event or Edit Existing Test Event, enter the parameters, and click OK.

    Event content:

    {
        "msg": "This is a test message"
    }
  2. Click Test Function to run the test.

    image

  3. Check if the recipient received the email.

    Note

    Some email servers might mark emails from unknown senders as spam. If you do not find the test email in your inbox, check your spam or junk folder.

Step 3: Create and configure a Function Compute node

  1. Log on to the DataWorks console. In the left-side navigation pane, click Workspaces.

  2. In the top navigation bar, switch to the same region that you specified in Step 1.

  3. On the Workspace List page, click the name of the target workspace to go to its details page. If you do not have a workspace in the current region, create one. For more information, see Create a workspace.

  4. In the left-side navigation pane, navigate to Data Development and O&M > DataStudio.

  5. Click the name of the target workflow. Right-click the General node and choose Function Compute. In the dialog box that appears, enter a name for the node and click Confirm to create the Function Compute node.

    image

  6. Configure the parameters for the Function Compute node.

    Parameter

    Description

    Select function

    Select the function that you created in Step 1.

    Select version or alias

    Select the version or alias to use when you invoke the function. The default version is LATEST. For more information, see Version management and Alias management.

    Invocation method

    Select Synchronous. For more information about invocation methods, see Synchronous invocation and Asynchronous invocation.

    Variables

    The parameters that you pass to the function. An example is provided below:

    {
        "msg": "This is a test message from dataworks!"
    }
  7. (Optional) Debug the Function Compute node. After you configure the node, you can click the 运行 icon to assign constant values to variables for a debug run.

  8. Configure the scheduling properties of the node. You can use DataWorks scheduling parameters to dynamically pass parameters to your code in scheduled runs. On the right side of the canvas, configure the scheduling configuration. For more information about scheduling parameters, see Supported formats of scheduling parameters. For more information about scheduling properties, see Configure task scheduling properties.

Step 4: Submit and publish the node

  1. Save and commit the node.

    Click the 保存 and 提交 icons in the toolbar to save and commit the node. In the commit dialog box, enter a change description and, if required, select the options for code review and smoke testing.

    Note
    • You must configure the Rerun attribute property and the Parent Nodes in the scheduling properties before you can commit the node.

    • If code review is enabled, the code of a submitted node must be approved by a reviewer before the node can be deployed. For more information, see Code review.

    • To ensure that the scheduled node runs as expected, we recommend that you perform smoke testing on the task before you deploy it. For more information, see Smoke testing.

  2. Optional. Deploy the node.

    If you are using a workspace in standard mode, you must click Deploy in the upper-right corner to deploy the node after you commit it. For more information, see Workspaces in standard mode and Deploy tasks.

Next steps