-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs: update email-server/send-email-using-platform
- Loading branch information
1 parent
0a77cc9
commit 4a60e47
Showing
6 changed files
with
172 additions
and
161 deletions.
There are no files selected for viewing
This file contains 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 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 |
---|---|---|
|
@@ -63,60 +63,71 @@ [email protected]`} | |
مقدار فیلد <Important>MAIL_FROM_ADDRESS</Important> باید یکی از نشانیهای اضافه شده در سرویس ایمیل باشد. | ||
</p> | ||
</Alert> | ||
<div className="h-2" /> | ||
|
||
در ادامه، بایستی با اجرای دستور زیر، ماژول موردنیاز ارسال ایمیل را در پروژه خود، دانلود و نصب کنید: | ||
|
||
<div className="h-2" /> | ||
<div dir='ltr'> | ||
<Highlight className="bash"> | ||
{`dotnet add package MailKit`} | ||
</Highlight> | ||
</div> | ||
<div className="h-2" /> | ||
|
||
در نهایت میتوانید در پروژهی خود مانند مثال زیر عمل کرده و با استفاده از دسترسی SMTP سرویس ایمیل لیارا، | ||
اقدام به ارسال ایمیلهای تراکنشی کنید: | ||
|
||
<div className="h-2" /> | ||
<div dir='ltr'> | ||
<Highlight className="dotnet"> | ||
{`using System.Net; | ||
using System.Net.Mail; | ||
using dotenv.net; | ||
DotEnv.Load(); // Load the environment variables from .env file | ||
{`using MailKit.Net.Smtp; | ||
using MimeKit; | ||
var builder = WebApplication.CreateBuilder(args); | ||
// Load environment variables | ||
var smtpHost = Environment.GetEnvironmentVariable("MAIL_HOST") ?? "smtp.c1.liara.email"; | ||
var smtpPort = int.Parse(Environment.GetEnvironmentVariable("MAIL_PORT") ?? "465"); | ||
var smtpUser = Environment.GetEnvironmentVariable("MAIL_USER") ?? ""; | ||
var smtpPassword = Environment.GetEnvironmentVariable("MAIL_PASSWORD") ?? ""; | ||
var mailFromAddress = Environment.GetEnvironmentVariable("MAIL_FROM_ADDRESS") ?? ""; | ||
var app = builder.Build(); | ||
app.MapGet("/send-test-email", async context => | ||
app.MapGet("/", async context => | ||
{ | ||
// Read SMTP settings from environment variables | ||
var smtpHost = Environment.GetEnvironmentVariable("MAIL_HOST"); | ||
int smtpPort = int.Parse(Environment.GetEnvironmentVariable("MAIL_PORT") ?? "587"); | ||
var smtpUser = Environment.GetEnvironmentVariable("MAIL_USER"); | ||
var smtpPassword = Environment.GetEnvironmentVariable("MAIL_PASSWORD"); | ||
var fromAddress = Environment.GetEnvironmentVariable("MAIL_FROM_ADDRESS") ?? "[email protected]"; | ||
var toAddress = "[email protected]"; // Replace with recipient's email address | ||
// Create a new SmtpClient | ||
using (var smtpClient = new SmtpClient(smtpHost, smtpPort)) | ||
var recipientEmail = "[email protected]"; // Replace with recipient email | ||
// Create the email | ||
var email = new MimeMessage(); | ||
email.From.Add(MailboxAddress.Parse(mailFromAddress)); | ||
email.To.Add(MailboxAddress.Parse(recipientEmail)); | ||
email.Subject = "Test Email"; | ||
email.Body = new TextPart("plain") | ||
{ | ||
smtpClient.EnableSsl = true; // Use TLS encryption | ||
smtpClient.Credentials = new NetworkCredential(smtpUser, smtpPassword); | ||
Text = "This is a test email sent using explicit TLS without STARTTLS." | ||
}; | ||
// Create the email message | ||
var mailMessage = new MailMessage(fromAddress, toAddress) | ||
{ | ||
Subject = "Test Email", | ||
Body = "<h2>This is a test email sent from a .NET Core application using SMTP<h2>", | ||
IsBodyHtml = true | ||
}; | ||
// Add custom headers | ||
mailMessage.Headers.Add("x-liara-tag", "test-tag"); | ||
// Add custom header | ||
email.Headers.Add("x-liara-tag", "test-tag"); | ||
try | ||
{ | ||
// Send the email | ||
try | ||
{ | ||
await smtpClient.SendMailAsync(mailMessage); | ||
await context.Response.WriteAsync("Test email sent successfully!"); | ||
} | ||
catch (Exception ex) | ||
{ | ||
await context.Response.WriteAsync($"Failed to send email: {ex.Message}"); | ||
} | ||
using var client = new SmtpClient(); | ||
await client.ConnectAsync(smtpHost, smtpPort, MailKit.Security.SecureSocketOptions.SslOnConnect); | ||
await client.AuthenticateAsync(smtpUser, smtpPassword); | ||
await client.SendAsync(email); | ||
await client.DisconnectAsync(true); | ||
// Respond to the client | ||
await context.Response.WriteAsync("Email sent successfully with custom header!"); | ||
} | ||
catch (Exception ex) | ||
{ | ||
// Handle errors and respond to the client | ||
await context.Response.WriteAsync($"Failed to send email: {ex.Message}"); | ||
} | ||
}); | ||
|
@@ -125,69 +136,67 @@ app.Run(); | |
</Highlight> | ||
</div> | ||
<div className="h-2" /> | ||
<Alert variant='info'> | ||
<p> | ||
با تنظیم <Important>EnableSsl = true</Important>، میتوانید بهصورت امن اقدام به ارسال ایمیلهای تراکنشی کنید. | ||
</p> | ||
</Alert> | ||
|
||
|
||
برای استفاده از ایمیلسرور در کنترلر، میتوانید مشابه قطعه کد زیر، عمل کنید: | ||
|
||
<div className="h-2" /> | ||
<div dir='ltr'> | ||
<Highlight className="csharp"> | ||
{`using MimeKit; | ||
using MailKit.Net.Smtp; | ||
using DotNetEnv; // for install this, run: dotnet install add package DotNetEnv | ||
{`using MailKit.Net.Smtp; | ||
using MimeKit; | ||
using Microsoft.AspNetCore.Mvc; | ||
namespace your_project_name.Controllers; | ||
public class TestController : Controller | ||
namespace EmailSenderApp.Controllers | ||
{ | ||
[HttpPost] | ||
public IActionResult SendEmail(string email) | ||
{ | ||
// Email Information | ||
Env.Load(); | ||
string senderName = Env.GetString("SENDER_NAME"); | ||
string senderEmail = Env.GetString("SENDER_ADDRESS"); | ||
string subject = Env.GetString("EMAIL_SUBJECT"); | ||
string body = Env.GetString("EMAIL_BODY"); | ||
// Email Instance | ||
var message = new MimeMessage(); | ||
message.From.Add(new MailboxAddress(senderName, senderEmail)); | ||
message.To.Add(new MailboxAddress("Recipient", email)); | ||
message.Subject = subject; | ||
// Creating The Body | ||
message.Body = new TextPart("plain") | ||
[Route("api/[controller]")] | ||
[ApiController] | ||
public class EmailController : ControllerBase | ||
{ | ||
// Load environment variables (or use default values) | ||
private readonly string smtpHost = Environment.GetEnvironmentVariable("MAIL_HOST") ?? "smtp.c1.liara.email"; | ||
private readonly int smtpPort = int.Parse(Environment.GetEnvironmentVariable("MAIL_PORT") ?? "465"); | ||
private readonly string smtpUser = Environment.GetEnvironmentVariable("MAIL_USER") ?? ""; | ||
private readonly string smtpPassword = Environment.GetEnvironmentVariable("MAIL_PASSWORD") ?? ""; | ||
private readonly string mailFromAddress = Environment.GetEnvironmentVariable("MAIL_FROM_ADDRESS") ?? ""; | ||
[HttpGet("send-test-email")] | ||
public async Task<IActionResult> SendTestEmail() | ||
{ | ||
Text = body | ||
}; | ||
var recipientEmail = "[email protected]"; // Replace with recipient email | ||
// Create the email | ||
var email = new MimeMessage(); | ||
email.From.Add(MailboxAddress.Parse(mailFromAddress)); | ||
email.To.Add(MailboxAddress.Parse(recipientEmail)); | ||
email.Subject = "Test Email"; | ||
email.Body = new TextPart("plain") | ||
{ | ||
Text = "This is a test email sent using explicit TLS without STARTTLS." | ||
}; | ||
try | ||
{ | ||
// Sending Email | ||
using (var client = new SmtpClient()) | ||
// Add custom header | ||
email.Headers.Add("x-liara-tag", "test-tag"); | ||
try | ||
{ | ||
client.Connect(Env.GetString("MAIL_HOST"), Env.GetInt("MAIL_PORT"), false); | ||
client.Authenticate(Env.GetString("MAIL_USERNAME"), Env.GetString("MAIL_PASSWORD")); | ||
client.Send(message); | ||
client.Disconnect(true); | ||
// Send the email | ||
using var client = new SmtpClient(); | ||
await client.ConnectAsync(smtpHost, smtpPort, MailKit.Security.SecureSocketOptions.SslOnConnect); | ||
await client.AuthenticateAsync(smtpUser, smtpPassword); | ||
await client.SendAsync(email); | ||
await client.DisconnectAsync(true); | ||
// Return success response | ||
return Ok("Email sent successfully with custom header!"); | ||
} | ||
catch (Exception ex) | ||
{ | ||
// Handle errors and return error response | ||
return StatusCode(500, $"Failed to send email: {ex.Message}"); | ||
} | ||
ViewBag.Message = "Email Sent Successfully."; | ||
} | ||
catch (Exception ex) | ||
{ | ||
ViewBag.Message = $"Error In Sending Email: {ex.Message}"; | ||
} | ||
return RedirectToAction("Index"); | ||
} | ||
} | ||
`} | ||
</Highlight> | ||
|
This file contains 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 |
---|---|---|
|
@@ -80,45 +80,46 @@ [email protected]`} | |
<div className="h-2" /> | ||
<div dir='ltr'> | ||
<Highlight className="python"> | ||
{`from flask import Flask, request | ||
from flask_mail import Mail, Message | ||
from dotenv import load_dotenv | ||
{`from flask import Flask, jsonify | ||
import smtplib | ||
from email.mime.text import MIMEText | ||
from email.mime.multipart import MIMEMultipart | ||
import os | ||
# Load environment variables from .env file | ||
load_dotenv() | ||
app = Flask(__name__) | ||
# Flask-Mail configuration | ||
app.config['MAIL_SERVER'] = os.getenv('MAIL_HOST') | ||
app.config['MAIL_PORT'] = int(os.getenv('MAIL_PORT')) | ||
app.config['MAIL_USERNAME'] = os.getenv('MAIL_USER') | ||
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD') | ||
app.config['MAIL_USE_TLS'] = True # Use TLS for encryption | ||
app.config['MAIL_USE_SSL'] = False # Don't use SSL, because we are using TLS | ||
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_FROM_ADDRESS') | ||
# Initialize Flask-Mail | ||
mail = Mail(app) | ||
# Email configuration from environment variables | ||
MAIL_HOST = os.getenv("MAIL_HOST", "smtp.c1.liara.email") | ||
MAIL_PORT = int(os.getenv("MAIL_PORT", 465)) | ||
MAIL_USER = os.getenv("MAIL_USER") | ||
MAIL_PASSWORD = os.getenv("MAIL_PASSWORD") | ||
MAIL_FROM_ADDRESS = os.getenv("MAIL_FROM_ADDRESS") | ||
MAIL_FROM_NAME = os.getenv("MAIL_FROM_NAME") | ||
@app.route('/send-test-email', methods=['GET']) | ||
@app.route("/", methods=["GET"]) | ||
def send_test_email(): | ||
try: | ||
# Create a message | ||
msg = Message(subject='Test Email from Flask', | ||
recipients=['[email protected]'], # Replace with the recipient's email address | ||
body='This is a test email sent from Flask using SMTP on Liara.', | ||
extra_headers = {"x-liara-tag": "test_tag"}) # Use liara tag feature | ||
# Send the email | ||
mail.send(msg) | ||
return 'Test email sent successfully!', 200 | ||
# Create email message | ||
msg = MIMEMultipart() | ||
msg["From"] = f"{MAIL_FROM_NAME} <{MAIL_FROM_ADDRESS}>" | ||
msg["To"] = "[email protected]" | ||
msg["Subject"] = "Test Email" | ||
msg["X-Liara-Tag"] = "test-tag" | ||
# Email body | ||
body = "This is a test email sent with Flask and forced SSL (TLS)." | ||
msg.attach(MIMEText(body, "plain")) | ||
# Connect to SMTP server using SSL | ||
with smtplib.SMTP_SSL(MAIL_HOST, MAIL_PORT) as server: | ||
server.login(MAIL_USER, MAIL_PASSWORD) | ||
server.sendmail(MAIL_FROM_ADDRESS, [MAIL_FROM_ADDRESS], msg.as_string()) | ||
return jsonify({"message": "Test email sent successfully!"}), 200 | ||
except Exception as e: | ||
return f'Failed to send email. Error: {str(e)}', 500 | ||
return jsonify({"error": str(e)}), 500 | ||
if __name__ == '__main__': | ||
if __name__ == "__main__": | ||
app.run(debug=True) | ||
`} | ||
</Highlight> | ||
|
Oops, something went wrong.