-
Notifications
You must be signed in to change notification settings - Fork 17.5k
Add Amazon SES hook #10004
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add Amazon SES hook #10004
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
7553235
Add Amazon SES hook
ipeluffo b264e3f
Add SES Hook to operators-and-hooks documentation.
ipeluffo 70ff896
Fix arguments for parent class constructor call (PR feedback)
ipeluffo b01dd5d
Fix indentation in operators-and-hooks documentation
ipeluffo 4ae49e9
Fix mypy error for argument on call to parent class constructor
ipeluffo a12c067
Simplify logic on constructor (PR feedback)
ipeluffo 5d83aeb
Add custom headers and other relevant options to hook
ipeluffo e28052b
Change pylint exception rule to apply it only to function instead of …
ipeluffo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, | ||
| # software distributed under the License is distributed on an | ||
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| # KIND, either express or implied. See the License for the | ||
| # specific language governing permissions and limitations | ||
| # under the License. | ||
|
|
||
| """ | ||
| This module contains AWS SES Hook | ||
| """ | ||
| from typing import Any, Dict, Iterable, List, Optional, Union | ||
|
|
||
| from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook | ||
| from airflow.utils.email import build_mime_message | ||
|
|
||
|
|
||
| class SESHook(AwsBaseHook): | ||
| """ | ||
| Interact with Amazon Simple Email Service. | ||
|
|
||
| Additional arguments (such as ``aws_conn_id``) may be specified and | ||
| are passed down to the underlying AwsBaseHook. | ||
|
|
||
| .. seealso:: | ||
| :class:`~airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook` | ||
| """ | ||
|
|
||
| def __init__(self, *args, **kwargs) -> None: | ||
| kwargs['client_type'] = 'ses' | ||
| super().__init__(*args, **kwargs) | ||
|
|
||
| def send_email( # pylint: disable=too-many-arguments | ||
| self, | ||
| mail_from: str, | ||
| to: Union[str, Iterable[str]], | ||
| subject: str, | ||
| html_content: str, | ||
| files: Optional[List[str]] = None, | ||
| cc: Optional[Union[str, Iterable[str]]] = None, | ||
| bcc: Optional[Union[str, Iterable[str]]] = None, | ||
| mime_subtype: str = 'mixed', | ||
| mime_charset: str = 'utf-8', | ||
| reply_to: Optional[str] = None, | ||
| return_path: Optional[str] = None, | ||
| custom_headers: Optional[Dict[str, Any]] = None | ||
| ) -> dict: | ||
| """ | ||
| Send email using Amazon Simple Email Service | ||
|
|
||
| :param mail_from: Email address to set as email's from | ||
| :param to: List of email addresses to set as email's to | ||
| :param subject: Email's subject | ||
| :param html_content: Content of email in HTML format | ||
| :param files: List of paths of files to be attached | ||
| :param cc: List of email addresses to set as email's CC | ||
| :param bcc: List of email addresses to set as email's BCC | ||
| :param mime_subtype: Can be used to specify the subtype of the message. Default = mixed | ||
| :param mime_charset: Email's charset. Default = UTF-8. | ||
| :param return_path: The email address to which replies will be sent. By default, replies | ||
| are sent to the original sender's email address. | ||
| :param reply_to: The email address to which message bounces and complaints should be sent. | ||
| "Return-Path" is sometimes called "envelope from," "envelope sender," or "MAIL FROM." | ||
| :param custom_headers: Additional headers to add to the MIME message. | ||
| No validations are run on these values and they should be able to be encoded. | ||
| :return: Response from Amazon SES service with unique message identifier. | ||
| """ | ||
| ses_client = self.get_conn() | ||
|
|
||
| custom_headers = custom_headers or {} | ||
| if reply_to: | ||
| custom_headers['Reply-To'] = reply_to | ||
| if return_path: | ||
| custom_headers['Return-Path'] = return_path | ||
|
|
||
| message, recipients = build_mime_message( | ||
| mail_from=mail_from, | ||
| to=to, | ||
| subject=subject, | ||
| html_content=html_content, | ||
| files=files, | ||
| cc=cc, | ||
| bcc=bcc, | ||
| mime_subtype=mime_subtype, | ||
| mime_charset=mime_charset, | ||
| custom_headers=custom_headers, | ||
| ) | ||
|
|
||
| return ses_client.send_raw_email( | ||
| Source=mail_from, Destinations=recipients, RawMessage={'Data': message.as_string()} | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, | ||
| # software distributed under the License is distributed on an | ||
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| # KIND, either express or implied. See the License for the | ||
| # specific language governing permissions and limitations | ||
| # under the License. | ||
|
|
||
| import boto3 | ||
| import pytest | ||
| from moto import mock_ses | ||
|
|
||
| from airflow.providers.amazon.aws.hooks.ses import SESHook | ||
|
|
||
| boto3.setup_default_session() | ||
|
|
||
|
|
||
| @mock_ses | ||
| def test_get_conn(): | ||
| hook = SESHook(aws_conn_id='aws_default') | ||
| assert hook.get_conn() is not None | ||
|
|
||
|
|
||
| @mock_ses | ||
| @pytest.mark.parametrize('to', | ||
| [ | ||
| 'to@domain.com', | ||
| ['to1@domain.com', 'to2@domain.com'], | ||
| 'to1@domain.com,to2@domain.com' | ||
| ]) | ||
| @pytest.mark.parametrize('cc', | ||
| [ | ||
| 'cc@domain.com', | ||
| ['cc1@domain.com', 'cc2@domain.com'], | ||
| 'cc1@domain.com,cc2@domain.com' | ||
| ]) | ||
| @pytest.mark.parametrize('bcc', | ||
| [ | ||
| 'bcc@domain.com', | ||
| ['bcc1@domain.com', 'bcc2@domain.com'], | ||
| 'bcc1@domain.com,bcc2@domain.com' | ||
| ]) | ||
| def test_send_email(to, cc, bcc): | ||
| # Given | ||
| hook = SESHook() | ||
| ses_client = hook.get_conn() | ||
| mail_from = 'test_from@domain.com' | ||
|
|
||
| # Amazon only allows to send emails from verified addresses, | ||
| # then we need to validate the from address before sending the email, | ||
| # otherwise this test would raise a `botocore.errorfactory.MessageRejected` exception | ||
| ses_client.verify_email_identity(EmailAddress=mail_from) | ||
|
|
||
| # When | ||
| response = hook.send_email( | ||
| mail_from=mail_from, | ||
| to=to, | ||
| subject='subject', | ||
| html_content='<html>Test</html>', | ||
| cc=cc, | ||
| bcc=bcc, | ||
| reply_to='reply_to@domain.com', | ||
| return_path='return_path@domain.com', | ||
| ) | ||
|
|
||
| # Then | ||
| assert response is not None | ||
| assert isinstance(response, dict) | ||
| assert 'MessageId' in response |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.