How to send a mail in wcf method
In WCF (Windows Communication Foundation), you can send an email using the System.Net.Mail
namespace. Here's an example of how you can do it in a WCF method:
Step 1: Add the necessary namespace
In your WCF service code, add the following namespace:
using System.Net.Mail;
Step 2: Create a MailMessage
object
Create a MailMessage
object to represent the email you want to send:
MailMessage mail = new MailMessage();
Step 3: Set the email properties
Set the properties of the MailMessage
object:
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Email subject";
mail.Body = "Email body";
Step 4: Create a SmtpClient
object
Create an SmtpClient
object to send the email:
SmtpClient client = new SmtpClient();
Step 5: Set the SMTP server settings
Set the SMTP server settings:
client.Host = "your-smtp-server-hostname";
client.Port = 587; // or 25, depending on your SMTP server
client.EnableSsl = true; // if your SMTP server requires SSL/TLS
client.Credentials = new NetworkCredential("your-smtp-server-username", "your-smtp-server-password");
Step 6: Send the email
Send the email using the Send
method:
client.Send(mail);
Example WCF method
Here's an example WCF method that sends an email:
[OperationContract]
public void SendEmail()
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Email subject";
mail.Body = "Email body";
SmtpClient client = new SmtpClient();
client.Host = "your-smtp-server-hostname";
client.Port = 587;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("your-smtp-server-username", "your-smtp-server-password");
client.Send(mail);
}
Note: Make sure to replace the placeholders ([email protected]
, [email protected]
, your-smtp-server-hostname
, your-smtp-server-username
, and your-smtp-server-password
) with your actual email address, recipient email address, SMTP server hostname, username, and password.