Skip to content

Add email sending functionality with Google SMTP - #54

Merged
abdulkeremkilic merged 10 commits into
JustJavaOrg:mainfrom
abdulkeremkilic:feat/34
Aug 10, 2025
Merged

Add email sending functionality with Google SMTP#54
abdulkeremkilic merged 10 commits into
JustJavaOrg:mainfrom
abdulkeremkilic:feat/34

Conversation

@abdulkeremkilic

@abdulkeremkilic abdulkeremkilic commented Aug 3, 2025

Copy link
Copy Markdown
Collaborator

Introduces MailService, MailController, and MailModel to enable sending emails via Google SMTP. Adds configuration classes and properties for SMTP settings, allowing email dispatch through a REST endpoint.
gymcorejpg

Summary by CodeRabbit

  • New Features

    • Added the ability to send emails via a new REST endpoint by specifying recipient, subject, and body.
    • Introduced support for Google SMTP configuration to enable email sending through Gmail.
    • Added configuration options for SMTP settings in the application properties.
  • Documentation

    • Included guidance comments in the configuration file for setting up email credentials securely.

Introduces MailService, MailController, and MailModel to enable sending emails via Google SMTP. Adds configuration classes and properties for SMTP settings, allowing email dispatch through a REST endpoint.
@coderabbitai

coderabbitai Bot commented Aug 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change introduces a complete email sending feature using Google SMTP in a Spring Boot application. It adds configuration classes for SMTP properties, a REST controller for sending emails, a service for handling email delivery via Jakarta Mail, a data model for email content, and new SMTP-related properties in the application configuration.

Changes

Cohort / File(s) Change Summary
SMTP Configuration Classes
src/main/java/org/justjava/gymcore/config/smtp/AbstractSmtpConfig.java, src/main/java/org/justjava/gymcore/config/smtp/GoogleSmtpConfig.java
Introduced an abstract base class for SMTP config with getters and setters for host, port, username, password, auth, and STARTTLS; added a Google SMTP-specific configuration class enabling Spring property binding.
Mail Sending REST API
src/main/java/org/justjava/gymcore/controller/MailController.java
Added a REST controller with a POST endpoint /sendMail/{to} accepting a MailModel to send emails via the mail service.
Mail Data Model
src/main/java/org/justjava/gymcore/model/MailModel.java
Introduced a Java record with validation annotations encapsulating immutable email subject and body fields.
Mail Sending Service
src/main/java/org/justjava/gymcore/service/MailService.java
Added a service that uses Jakarta Mail API and injected Google SMTP configuration to construct and send emails, returning HTTP status.
Application Properties
src/main/resources/application.properties
Added Google SMTP-related properties including host, port, authentication, username, password, and STARTTLS settings with security guidance comments.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MailController
    participant MailService
    participant GoogleSmtpConfig
    participant SMTPServer

    Client->>MailController: POST /mail/sendMail/{to} (MailModel)
    MailController->>MailService: sendMail(to, subject, body)
    MailService->>GoogleSmtpConfig: get SMTP properties
    MailService->>SMTPServer: Send email via Jakarta Mail
    SMTPServer-->>MailService: Response (success/failure)
    MailService-->>MailController: ResponseEntity<HttpStatus>
    MailController-->>Client: HTTP Response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

From burrows deep, a rabbit hops,
Now emails fly with clever props!
SMTP set, the config’s neat,
A RESTful hop, delivery complete.
With subject and body, the message goes—
Through springy fields, where Gmail flows!
🐇✉️

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6c72aef and 333cccc.

📒 Files selected for processing (1)
  • src/main/java/org/justjava/gymcore/service/MailService.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/org/justjava/gymcore/service/MailService.java
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 12

🧹 Nitpick comments (3)
src/main/java/org/justjava/gymcore/config/smtp/GoogleSmtpConfig.java (1)

6-9: LGTM! Consider adding configuration validation.

The configuration class structure is correct and follows Spring Boot best practices. The use of @ConfigurationProperties with prefix binding is appropriate.

Consider adding validation to ensure configuration completeness:

+import jakarta.validation.constraints.NotBlank;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.validation.annotation.Validated;
+
 @Configuration
+@Validated
+@EnableConfigurationProperties
 @ConfigurationProperties(prefix = "smtp.google")
 public class GoogleSmtpConfig extends AbstractSmtpConfig {
+    
+    @Override
+    @NotBlank(message = "SMTP host must be configured")
+    public void setHost(String host) {
+        super.setHost(host);
+    }
+    
+    @Override
+    @NotBlank(message = "SMTP username must be configured")  
+    public void setUsername(String username) {
+        super.setUsername(username);
+    }
 }
src/main/java/org/justjava/gymcore/controller/MailController.java (1)

17-17: Consider using request body for recipient email instead of path variable.

Using email address as a path variable can cause issues with URL encoding and special characters commonly found in email addresses.

Consider moving the recipient email to the request body:

+public record MailRequest(
+    @Email(message = "Invalid recipient email address")
+    @NotBlank(message = "Recipient email is required")
+    String to,
+    @NotBlank(message = "Email subject cannot be blank")
+    String subject,
+    @NotBlank(message = "Email body cannot be blank") 
+    String body
+) {}

-    @PostMapping("/sendMail/{to}")
-    public ResponseEntity<String> sendMail(@PathVariable("to") String to, @RequestBody MailModel mailModel) {
+    @PostMapping("/sendMail")
+    public ResponseEntity<String> sendMail(@Valid @RequestBody MailRequest mailRequest) {
+        return mailService.sendMail(mailRequest.to(), mailRequest.subject(), mailRequest.body());
     }
src/main/java/org/justjava/gymcore/service/MailService.java (1)

25-25: Consider removing or clarifying the comment.

The comment mentions "yaml file" but the configuration appears to be using properties files based on the AI summary. This could be misleading.

Either update the comment to reflect the actual configuration method or remove it if it's not adding value:

-    // Host, Host e-mail, password and port will be provided under yaml file. If you want to get configurations from yaml file use smtpConfigurationService.
+    // SMTP configuration is provided via GoogleSmtpConfig from application properties
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 992d832 and 817875c.

📒 Files selected for processing (6)
  • src/main/java/org/justjava/gymcore/config/smtp/AbstractSmtpConfig.java (1 hunks)
  • src/main/java/org/justjava/gymcore/config/smtp/GoogleSmtpConfig.java (1 hunks)
  • src/main/java/org/justjava/gymcore/controller/MailController.java (1 hunks)
  • src/main/java/org/justjava/gymcore/model/MailModel.java (1 hunks)
  • src/main/java/org/justjava/gymcore/service/MailService.java (1 hunks)
  • src/main/resources/application.properties (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Build

Comment thread src/main/java/org/justjava/gymcore/controller/MailController.java Outdated
Comment thread src/main/java/org/justjava/gymcore/controller/MailController.java
Comment thread src/main/java/org/justjava/gymcore/model/MailModel.java Outdated
Comment thread src/main/java/org/justjava/gymcore/service/MailService.java Outdated
Comment thread src/main/java/org/justjava/gymcore/service/MailService.java
Comment thread src/main/java/org/justjava/gymcore/service/MailService.java Outdated
Comment thread src/main/java/org/justjava/gymcore/service/MailService.java Outdated
Comment thread src/main/resources/application.properties
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/main/java/org/justjava/gymcore/model/MailModel.java (1)

6-15: Validation constraints properly implemented from previous review.

The validation annotations have been correctly added as suggested in the previous review, with appropriate constraints for email subject and body fields following RFC 5322 standards.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 817875c and 19e9ff7.

📒 Files selected for processing (1)
  • src/main/java/org/justjava/gymcore/model/MailModel.java (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Build
src/main/java/org/justjava/gymcore/model/MailModel.java

[error] 16-16: Compilation error: class, interface, enum, or record expected. Likely a syntax error such as an unmatched closing brace '}'.

Comment thread src/main/java/org/justjava/gymcore/model/MailModel.java Outdated
Adjusted indentation in MailModel.java for improved readability and consistency. No functional changes were made.
@frank-connolly

Copy link
Copy Markdown
Collaborator

Great work here Abdul. We are using some AI powered code reviews on Pull Requests as a way to try these new tools. Take a look over its suggestions and see if you agree with any of the suggestions. Resolve them if not. We'll review after.

abdulkeremkilic and others added 5 commits August 4, 2025 23:17
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Changed sendMail return type to ResponseEntity<HttpStatus> and replaced logger usage with log for better logging. Enhanced success and error log messages for email sending.
@abdulkeremkilic

Copy link
Copy Markdown
Collaborator Author

All resolved.

Comment thread src/main/java/org/justjava/gymcore/service/MailService.java Outdated
Comment thread src/main/java/org/justjava/gymcore/service/MailService.java Outdated
Comment thread src/main/java/org/justjava/gymcore/controller/MailController.java Outdated

@ozkanpakdil ozkanpakdil left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Needs input validation and some tidying up.

Refactored MailController and MailService to provide better error handling and email address validation. MailController now returns a success or error message, and MailService throws MessagingException instead of handling it internally. Removed unused imports and simplified constructor usage with Lombok's @requiredargsconstructor.
@abdulkeremkilic

Copy link
Copy Markdown
Collaborator Author

Thank you for reviews @ozkanpakdil . I commited new changes.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/main/java/org/justjava/gymcore/service/MailService.java (1)

18-18: Fix dependency injection by making the field final.

The GoogleSmtpConfig field is not final, so @RequiredArgsConstructor won't generate a constructor parameter for it, leading to a NullPointerException when accessed.

Apply this diff to fix the dependency injection:

-    private GoogleSmtpConfig googleSmtpConfig;
+    private final GoogleSmtpConfig googleSmtpConfig;
🧹 Nitpick comments (1)
src/main/java/org/justjava/gymcore/service/MailService.java (1)

38-45: Add input validation for robustness.

Consider adding basic input validation to handle null or empty parameters gracefully before creating the message.

Apply this diff to add input validation:

+        if (to == null || to.trim().isEmpty()) {
+            throw new IllegalArgumentException("Recipient email address cannot be null or empty");
+        }
+        if (subject == null) subject = "";
+        if (body == null) body = "";
+
         Message message = new MimeMessage(session);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3dec3aa and 6c72aef.

📒 Files selected for processing (2)
  • src/main/java/org/justjava/gymcore/controller/MailController.java (1 hunks)
  • src/main/java/org/justjava/gymcore/service/MailService.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/org/justjava/gymcore/controller/MailController.java
🔇 Additional comments (2)
src/main/java/org/justjava/gymcore/service/MailService.java (2)

21-21: Excellent improvement to method signature.

The method signature now properly follows service layer patterns by returning void and throwing MessagingException instead of mixing HTTP concerns with business logic.


37-37: Good use of thread-safe Session.getInstance().

Correctly uses Session.getInstance() instead of the deprecated Session.getDefaultInstance(), ensuring thread safety in multi-threaded environments.

Changed googleSmtpConfig to be final in MailService to ensure immutability and proper usage with @requiredargsconstructor.

@ozkanpakdil ozkanpakdil left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@abdulkeremkilic
abdulkeremkilic merged commit 17aa47e into JustJavaOrg:main Aug 10, 2025
2 checks passed
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.

3 participants