SmtpClient with configuration from appsettings.json.
Overview
The email sending feature allows your application to send HTML emails using SMTP. Configuration is externalized to settings files for easy environment-specific changes.Complete Implementation
Configure Email Settings
Add email configuration to your
appsettings.json or appsettings.Development.json.appsettings.json
Common SMTP Providers
| Provider | Host | Port | SSL |
|---|---|---|---|
| Gmail | smtp.gmail.com | 587 | true |
| Outlook | smtp-mail.outlook.com | 587 | true |
| Office 365 | smtp.office365.com | 587 | true |
| SendGrid | smtp.sendgrid.net | 587 | true |
Create the Mail Controller
The controller reads SMTP settings from configuration and sends emails.See MailsController.cs:21
Controllers/MailsController.cs
Important: Set
UseDefaultCredentials = false BEFORE setting custom credentials. The order matters!How It Works
Email Sending Workflow
Reading Configuration
Usage Example
- Navigate to
/Mails/SendMail - Enter recipient email address in “To” field
- Enter subject in “Asunto” field
- Enter message body (supports HTML) in “Mensaje” field
- Click “Send mail”
- Success message displays when sent
Gmail Configuration
For Gmail accounts, you need to use an App Password instead of your regular password.Generate App Password
- Go to Google App Passwords
- Select “Mail” and “Other (Custom name)”
- Copy the 16-character password
Advanced Features
Sending HTML Emails
Adding Attachments
Multiple Recipients
Custom Priority
Error Handling
Common Issues
Authentication Failed
Authentication Failed
Causes:
- Wrong username/password
- Gmail: Not using App Password
- 2FA not enabled (Gmail)
- Verify credentials in appsettings.json
- Generate and use App Password for Gmail
Connection Refused / Timeout
Connection Refused / Timeout
Causes:
- Wrong host or port
- SSL setting mismatch
- Firewall blocking SMTP
- Verify host and port for your provider
- Check SSL setting matches provider requirements
- Test SMTP connectivity from your server
UseDefaultCredentials Error
UseDefaultCredentials Error
Cause:
- Setting custom credentials before
UseDefaultCredentials = false
- Always set
UseDefaultCredentials = falseFIRST - Then set
Credentialsproperty
Production Recommendations
Best Practices:
- Use dedicated email service (SendGrid, AWS SES, etc.)
- Implement email queue for reliability
- Add retry logic for failed sends
- Log email sending attempts
- Validate email addresses before sending
- Rate limit to prevent abuse
Alternative: Consider using dedicated email libraries like:
- MailKit (modern, cross-platform)
- FluentEmail (fluent interface)
- SendGrid SDK (if using SendGrid)
Related
MailsController
Complete API reference for email controller
Email Utility
Learn more about email configuration and features