Skip to content
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

fix smtp mail sending #26

Merged
merged 2 commits into from
Oct 26, 2024
Merged

Conversation

jokester
Copy link
Member

@jokester jokester commented Oct 26, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced email sending functionality with improved connection clarity.
  • Bug Fixes

    • Refined error handling for SMTP connections, including better feedback for unsupported STARTTLS commands.
  • Improvements

    • Updated login method for better alignment with user credentials and enhanced error reporting with SMTP error codes.

@jokester jokester marked this pull request as ready for review October 26, 2024 19:46
Copy link

coderabbitai bot commented Oct 26, 2024

Walkthrough

The changes in this pull request primarily focus on enhancing the email_task function within app/tasks/email.py. Modifications include the addition of an email_smtp_port parameter to the SMTP connection constructors, improved error handling for the STARTTLS command, and updates to the login method to utilize from_username. These adjustments aim to clarify connection processes and provide more detailed error feedback.

Changes

File Change Summary
app/tasks/email.py - Added email_smtp_port parameter to smtplib.SMTP_SSL and smtplib.SMTP constructors.
- Introduced a try-except block around client.starttls() to handle smtplib.SMTPNotSupportedError.
- Updated login method to use from_username instead of from_address.
- Modified return messages for exceptions to include SMTP error codes and messages.
- Updated method signatures for email_task and send_email with modified logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant EmailService
    participant SMTPClient

    User->>EmailService: send_email()
    EmailService->>SMTPClient: connect(email_smtp_port)
    SMTPClient->>SMTPClient: starttls()
    alt STARTTLS not supported
        SMTPClient-->>EmailService: SMTPNotSupportedError
    else STARTTLS supported
        SMTPClient->>SMTPClient: login(from_username)
        SMTPClient->>User: Email sent successfully
    end
Loading

🐰 "In the garden where emails fly,
A rabbit hops, oh my, oh my!
With ports and SMTP in play,
Error handling saves the day!
From username, we send with glee,
Hopping high, as happy as can be!" 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@@ -60,13 +60,18 @@ def email_task(
try:
# 是否使用ssl
if email_use_ssl:
client = smtplib.SMTP_SSL(email_smtp_host)
client = smtplib.SMTP_SSL(email_smtp_host, email_smtp_port)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SMTP_SSL and SMTP constructors already do connect() inside. port must be given before that connect call.

# 开启DEBUG模式
client.set_debuglevel(0)
client.login(from_address, email_password)
client.login(from_username, email_password)
Copy link
Member Author

@jokester jokester Oct 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be the smtp auth user

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
app/tasks/email.py (1)

Line range hint 81-92: Add logging for better error tracking

While the error handling is comprehensive, adding logging would help with debugging and monitoring in production.

Consider adding logging:

+import logging
+
+logger = logging.getLogger(__name__)
+
 def email_task(...):
     try:
         # ... existing code ...
     except smtplib.SMTPConnectError as e:
+        logger.error(f"SMTP connection error: {e.smtp_code} - {e.smtp_error}")
         return "发送失败,连接失败:", str(e.smtp_code), str(e.smtp_error)
     # Add similar logging for other exceptions
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c36e115 and 41ae593.

📒 Files selected for processing (1)
  • app/tasks/email.py (1 hunks)
🔇 Additional comments (3)
app/tasks/email.py (3)

63-63: LGTM: Explicit port specification improves reliability

The addition of email_smtp_port parameter to SMTP constructors ensures consistent port usage regardless of the server configuration.

Also applies to: 65-65


66-71: Review STARTTLS implementation and security implications

While the error handling for STARTTLS is correct, there are a few considerations:

  1. The commented out ehlo_or_helo_if_needed() should either be implemented or removed, as it's typically required after STARTTLS.
  2. Silently continuing without STARTTLS could expose credentials over an unencrypted connection.

Consider this improved implementation:

 if not email_use_ssl:
     try:
         client.starttls()
-        # client.ehlo_or_helo_if_needed()
+        client.ehlo()  # Required after STARTTLS
     except smtplib.SMTPNotSupportedError:
-        pass
+        if celery.conf.app_config.get('EMAIL_REQUIRE_TLS', True):
+            raise  # Don't proceed without encryption if TLS is required

74-74: LGTM: Correct use of from_username for authentication

Using from_username for SMTP authentication is the right approach. The error handling for authentication failures is also properly implemented.

Let's verify the username validation:

✅ Verification successful

Let me check how the from_username is validated and used in the email sending logic.


Let me check the email task implementation to see how from_username is handled.


LGTM: Username validation is properly implemented

The code correctly handles the from_username parameter:

  • Falls back to EMAIL_USERNAME config if from_username is None
  • Uses the username for both SMTP authentication and email "From" header
  • Configuration validation is done via the ENABLE_USER_EMAIL check
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if from_username is properly validated before use
rg -g '!*.pyc' -g '!*test*' "from_username.*=.*None" -A 5

Length of output: 590


Script:

#!/bin/bash
# Check email sending implementation for username validation and usage
rg -g '!*.pyc' -g '!*test*' "def.*send.*mail" -A 20 app/tasks/email.py

Length of output: 598


Script:

#!/bin/bash
# Check email task implementation
rg -g '!*.pyc' -g '!*test*' "@celery.*task.*email" -A 30 app/tasks/email.py

Length of output: 1248

@jokester jokester merged commit 9254cf0 into moeflow-com:main Oct 26, 2024
4 checks passed
@jokester jokester deleted the fix-smtp-nondefault-port branch October 26, 2024 19:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant