- 
                Notifications
    
You must be signed in to change notification settings  - Fork 139
 
Add support for Mailtrap #406
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
          
     Draft
      
      
            cahna
  wants to merge
  3
  commits into
  anymail:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
cahna:mailtrap
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Draft
                    Changes from all commits
      Commits
    
    
  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
    
  
  
    
              
  
    
      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,276 @@ | ||
| import sys | ||
| from urllib.parse import quote | ||
| 
     | 
||
| if sys.version_info < (3, 11): | ||
| from typing_extensions import Any, Dict, List, Literal, NotRequired, TypedDict | ||
| else: | ||
| from typing import Any, Dict, List, Literal, NotRequired, TypedDict | ||
| 
     | 
||
| from ..exceptions import AnymailRequestsAPIError | ||
| from ..message import AnymailMessage, AnymailRecipientStatus | ||
| from ..utils import Attachment, EmailAddress, get_anymail_setting, update_deep | ||
| from .base_requests import AnymailRequestsBackend, RequestsPayload | ||
| 
     | 
||
| 
     | 
||
| class MailtrapAddress(TypedDict): | ||
| email: str | ||
| name: NotRequired[str] | ||
| 
     | 
||
| 
     | 
||
| class MailtrapAttachment(TypedDict): | ||
| content: str | ||
| type: NotRequired[str] | ||
| filename: str | ||
| disposition: NotRequired[Literal["attachment", "inline"]] | ||
| content_id: NotRequired[str] | ||
| 
     | 
||
| 
     | 
||
| MailtrapData = TypedDict( | ||
| "MailtrapData", | ||
| { | ||
| # Although "from" and "subject" are technically required, | ||
| # allow Mailtrap's API to enforce that. | ||
| "from": NotRequired[MailtrapAddress], | ||
| "to": NotRequired[List[MailtrapAddress]], | ||
| "cc": NotRequired[List[MailtrapAddress]], | ||
| "bcc": NotRequired[List[MailtrapAddress]], | ||
| "attachments": NotRequired[List[MailtrapAttachment]], | ||
| "headers": NotRequired[Dict[str, str]], | ||
| "custom_variables": NotRequired[Dict[str, str]], | ||
| "subject": NotRequired[str], | ||
| "text": NotRequired[str], | ||
| "html": NotRequired[str], | ||
| "category": NotRequired[str], | ||
| "template_uuid": NotRequired[str], | ||
| "template_variables": NotRequired[Dict[str, Any]], | ||
| }, | ||
| ) | ||
| 
     | 
||
| 
     | 
||
| class MailtrapPayload(RequestsPayload): | ||
| def __init__( | ||
| self, | ||
| message: AnymailMessage, | ||
| defaults, | ||
| backend: "EmailBackend", | ||
| *args, | ||
| **kwargs, | ||
| ): | ||
| http_headers = { | ||
| "Api-Token": backend.api_token, | ||
| "Content-Type": "application/json", | ||
| "Accept": "application/json", | ||
| } | ||
| # Yes, the parent sets this, but setting it here, too, gives type hints | ||
| self.backend = backend | ||
| self.metadata = None | ||
| 
     | 
||
| # needed for backend.parse_recipient_status | ||
| self.recipients_to: List[str] = [] | ||
| self.recipients_cc: List[str] = [] | ||
| self.recipients_bcc: List[str] = [] | ||
                
      
                  cahna marked this conversation as resolved.
               
          
            Show resolved
            Hide resolved
         | 
||
| 
     | 
||
| super().__init__( | ||
| message, defaults, backend, *args, headers=http_headers, **kwargs | ||
| ) | ||
| 
     | 
||
| def get_api_endpoint(self): | ||
| if self.backend.use_sandbox: | ||
| test_inbox_id = quote(str(self.backend.test_inbox_id), safe="") | ||
| return f"send/{test_inbox_id}" | ||
| return "send" | ||
| 
     | 
||
| def serialize_data(self): | ||
| return self.serialize_json(self.data) | ||
| 
     | 
||
| # | ||
| # Payload construction | ||
| # | ||
| 
     | 
||
| def init_payload(self): | ||
| self.data: MailtrapData = {} | ||
| 
     | 
||
| @staticmethod | ||
| def _mailtrap_email(email: EmailAddress) -> MailtrapAddress: | ||
| """Expand an Anymail EmailAddress into Mailtrap's {"email", "name"} dict""" | ||
| result = {"email": email.addr_spec} | ||
| if email.display_name: | ||
| result["name"] = email.display_name | ||
| return result | ||
| 
     | 
||
| def set_from_email(self, email: EmailAddress): | ||
| self.data["from"] = self._mailtrap_email(email) | ||
| 
     | 
||
| def set_recipients( | ||
| self, recipient_type: Literal["to", "cc", "bcc"], emails: List[EmailAddress] | ||
| ): | ||
| assert recipient_type in ["to", "cc", "bcc"] | ||
| if emails: | ||
| self.data[recipient_type] = [ | ||
| self._mailtrap_email(email) for email in emails | ||
| ] | ||
| 
     | 
||
| if recipient_type == "to": | ||
| self.recipients_to = [email.addr_spec for email in emails] | ||
| elif recipient_type == "cc": | ||
| self.recipients_cc = [email.addr_spec for email in emails] | ||
| elif recipient_type == "bcc": | ||
| self.recipients_bcc = [email.addr_spec for email in emails] | ||
| 
     | 
||
| def set_subject(self, subject): | ||
| if subject: | ||
| # (must ignore default empty subject for use with template_uuid) | ||
| self.data["subject"] = subject | ||
| 
     | 
||
| def set_reply_to(self, emails: List[EmailAddress]): | ||
| if emails: | ||
| # Use header rather than "reply_to" param | ||
| # to allow multiple reply-to addresses | ||
| self.data.setdefault("headers", {})["Reply-To"] = ", ".join( | ||
| email.address for email in emails | ||
| ) | ||
| 
     | 
||
| def set_extra_headers(self, headers): | ||
| self.data.setdefault("headers", {}).update(headers) | ||
| 
     | 
||
| def set_text_body(self, body): | ||
| if body: | ||
| self.data["text"] = body | ||
| 
     | 
||
| def set_html_body(self, body): | ||
| if "html" in self.data: | ||
| # second html body could show up through multiple alternatives, | ||
| # or html body + alternative | ||
| self.unsupported_feature("multiple html parts") | ||
| self.data["html"] = body | ||
| 
     | 
||
| def add_attachment(self, attachment: Attachment): | ||
| att: MailtrapAttachment = { | ||
| # Mailtrap requires filename even for inline attachments. | ||
| # Provide a fallback filename like the Mailjet backend does. | ||
| "filename": attachment.name or "attachment", | ||
| "content": attachment.b64content, | ||
| # default disposition is "attachment" | ||
| } | ||
| if attachment.mimetype: | ||
| att["type"] = attachment.mimetype | ||
| if attachment.inline: | ||
| att["disposition"] = "inline" | ||
| att["content_id"] = attachment.cid | ||
| self.data.setdefault("attachments", []).append(att) | ||
| 
     | 
||
| def set_tags(self, tags: List[str]): | ||
| if len(tags) > 1: | ||
| self.unsupported_feature("multiple tags") | ||
| if len(tags) > 0: | ||
| self.data["category"] = tags[0] | ||
| 
     | 
||
| def set_metadata(self, metadata): | ||
| self.data.setdefault("custom_variables", {}).update( | ||
| {str(k): str(v) for k, v in metadata.items()} | ||
| ) | ||
| self.metadata = metadata # save for set_merge_metadata | ||
| 
     | 
||
| def set_template_id(self, template_id): | ||
| self.data["template_uuid"] = template_id | ||
| 
     | 
||
| def set_merge_global_data(self, merge_global_data: Dict[str, Any]): | ||
| self.data.setdefault("template_variables", {}).update(merge_global_data) | ||
| 
     | 
||
| def set_esp_extra(self, extra): | ||
| update_deep(self.data, extra) | ||
| 
     | 
||
| 
     | 
||
| class EmailBackend(AnymailRequestsBackend): | ||
| """ | ||
| Mailtrap API Email Backend | ||
| """ | ||
| 
     | 
||
| esp_name = "Mailtrap" | ||
| 
     | 
||
| DEFAULT_API_URL = "https://send.api.mailtrap.io/api/" | ||
| DEFAULT_SANDBOX_API_URL = "https://sandbox.api.mailtrap.io/api/" | ||
| 
     | 
||
| def __init__(self, **kwargs): | ||
| """Init options from Django settings""" | ||
| self.api_token = get_anymail_setting( | ||
| "api_token", esp_name=self.esp_name, kwargs=kwargs, allow_bare=True | ||
| ) | ||
| self.test_inbox_id = get_anymail_setting( | ||
| "test_inbox_id", esp_name=self.esp_name, kwargs=kwargs, default=None | ||
| ) | ||
| self.use_sandbox = self.test_inbox_id is not None | ||
| 
     | 
||
| api_url = get_anymail_setting( | ||
| "api_url", | ||
| esp_name=self.esp_name, | ||
| kwargs=kwargs, | ||
| default=( | ||
| self.DEFAULT_SANDBOX_API_URL | ||
| if self.use_sandbox | ||
| else self.DEFAULT_API_URL | ||
| ), | ||
| ) | ||
| if not api_url.endswith("/"): | ||
| api_url += "/" | ||
| 
     | 
||
| super().__init__(api_url, **kwargs) | ||
| 
     | 
||
| def build_message_payload(self, message, defaults): | ||
| return MailtrapPayload(message, defaults, self) | ||
| 
     | 
||
| def parse_recipient_status( | ||
| self, response, payload: MailtrapPayload, message: AnymailMessage | ||
| ): | ||
| parsed_response = self.deserialize_json_response(response, payload, message) | ||
| 
     | 
||
| if parsed_response.get("errors") or not parsed_response.get("success"): | ||
| # Superclass has already filtered error status responses, so this shouldn't happen. | ||
| status = response.status_code | ||
| raise AnymailRequestsAPIError( | ||
| f"Unexpected API failure fields with response status {status}", | ||
| email_message=message, | ||
| payload=payload, | ||
| response=response, | ||
| backend=self, | ||
| ) | ||
| 
     | 
||
| try: | ||
| message_ids = parsed_response["message_ids"] | ||
| except KeyError: | ||
| raise AnymailRequestsAPIError( | ||
| "Unexpected API response format", | ||
| email_message=message, | ||
| payload=payload, | ||
| response=response, | ||
| backend=self, | ||
| ) | ||
| 
     | 
||
| # The sandbox API always returns a single message id for all recipients; | ||
| # the production API returns one message id per recipient in this order: | ||
| recipients = [ | ||
| *payload.recipients_to, | ||
| *payload.recipients_cc, | ||
| *payload.recipients_bcc, | ||
| ] | ||
| expected_count = 1 if self.use_sandbox else len(recipients) | ||
| actual_count = len(message_ids) | ||
| if expected_count != actual_count: | ||
| raise AnymailRequestsAPIError( | ||
| f"Expected {expected_count} message_ids, got {actual_count}", | ||
| email_message=message, | ||
| payload=payload, | ||
| response=response, | ||
| backend=self, | ||
| ) | ||
| if self.use_sandbox: | ||
| message_ids = [message_ids[0]] * len(recipients) | ||
| 
     | 
||
| recipient_status = { | ||
| email: AnymailRecipientStatus( | ||
| message_id=message_id, | ||
| status="sent", | ||
| ) | ||
| for email, message_id in zip(recipients, message_ids) | ||
| } | ||
| return recipient_status | ||
  
    
      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
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
      
      Oops, something went wrong.
        
    
  
  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.