---
# System prepended metadata

title: C# - Mail
tags: [C#]

---

---
tags: C#
---

# C# - Mail

## 1. 使用 [System.Net.Mail](https://docs.microsoft.com/zh-tw/dotnet/api/system.net.mail?view=netframework-4.8)

```csharp=
using System.Net.Mail;
```

### 設定寄件者和收件者email

使用 [MailAddress](https://docs.microsoft.com/zh-tw/dotnet/api/system.net.mail.mailaddress?view=netframework-4.8) 表示電子郵件寄件者或收件者的地址。

```csharp=
MailMessage message = new MailMessage();
message.From = new MailAddress("Sendername <Sender Email>");
message.To.Add(new MailAddress("Receiver Email"));

// 寄副本
message.CC.Add(new MailAddress("Another Receiver Email"));
// 寄密件副本
message.Bcc.Add(new MailAddress("Another Receiver Email"));
```

### 設定信件內容

使用 [MailMessage](https://docs.microsoft.com/zh-tw/dotnet/api/system.net.mail.mailmessage?view=netframework-4.8) 表示電子郵件內容

```csharp=
message.Subject = "How you doin'?";
message.Body = new TextPart("plain")
{
    Text = @"Hey Chandler,

    I just wanted to let you know that Monica and I were going to go play some paintball, you in?

    -- Joey"
};
```

### 設定 Smtp 及寄信 (以 Outlook 為例)

使用 [SmtpClient](https://docs.microsoft.com/zh-tw/dotnet/api/system.net.mail.smtpclient?view=netframework-4.8
) 設定 Smtp 主機

```csharp=
SmtpClient client = new SmtpClient();
client.Host = "smtp.live.com";
client.Port = 587;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("Account", "Password");

client.Send(message);
```

| Mail Service      | Smtp Address        |
| ----------------- | ------------------- |
| Yahoo             | smtp.mail.yahoo.com |
| Gmail             | smtp.gmail.com      |
| Hotmail (Outlook) | smtp.live.com       |

## 2. 使用 [MailKit](https://github.com/jstedfast/MailKit)

```csharp=
using MailKit.Net.Smtp;
using MimeKit;
```

### 設定寄件者和收件者email

```csharp=
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Sender name", "Sender Email"));
message.To.Add(new MailboxAddress("Receiver name", "Receiver Email"));

// 寄副本
message.Cc.Add(new MailAddress("Another Receiver Email"));
// 寄密件副本
message.Bcc.Add(new MailAddress("Another Receiver Email"));
```

### 設定信件內容

```csharp=
message.Subject = "How you doin'?";
message.Body = new TextPart("plain")
{
    Text = @"Hey Chandler,

    I just wanted to let you know that Monica and I were going to go play some paintball, you in?

    -- Joey"
};
```

### 設定 Smtp 及寄信 (以 Outlook 為例)

```csharp=
using (var client = new SmtpClient())
{
    client.Connect("smtp.live.com", 587);

    // Note: only needed if the SMTP server requires authentication
    client.Authenticate("Account", "Password");

    client.Send(message);
    client.Disconnect(true);
}
```