如何请求操作系统在 C# 中发送电子邮件
本文关键字:电子邮件 操作系统 何请求 请求 | 更新日期: 2024-11-08 23:38:15
如何请求操作系统发送包含特定主题、正文和附件的电子邮件?操作系统是否应该启动预加载字段的默认电子邮件客户端?
具体来说,C#.net 中有哪些 API 函数可用?
由于您希望 Outlook 发送电子邮件,请将端口号和主机替换为 Outlook 的端口号和主机。
若要使用预加载字段打开 Outlook,请执行以下操作:
using System.Diagnostics;
// ...
Process.Start(String.Format("mailto:{0}?subject={1}&cc={2}&bcc={3}&body={4}", address, subject, cc, bcc, body))
要直接发送电子邮件:
using System.Net;
using System.Net.Mail;
// ...
var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient {
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using(var message = new MailMessage(fromAddress, toAddress) {
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
这是一个用于系统SmtpClient
的简单适配器,可以简化您的测试。
public class SmtpClientAdapter : ISmtpClient
{
private bool disposed;
private SmtpClient smtpClient = new SmtpClient();
public SendResult Send(MailMessage message)
{
if (disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
try
{
smtpClient.Send(message);
return SendResult.Successful;
}
catch (Exception e)
{
return new SendResult(false, e.Message);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
if (smtpClient != null)
{
smtpClient.Dispose();
smtpClient = null;
}
}
disposed = true;
}
}
public class SendResult : SimpleResult
{
public SendResult(bool success, string message)
: base(success, message)
{
}
public static SendResult Successful
{
get
{
return new SendResult(true, string.Empty);
}
}
}
用法
var emailFrom = new MailAddress(sender);
var emailTo = new MailAddress(recipient);
var mailMessage = new MailMessage(emailFrom, emailTo)
{
Subject = "Subject ",
Body = "Body"
};
using (var client = new SmtpClientAdapter())
{
return client.Send(mailMessage);
}
这是一个简单的方法,
public void SendEmail(string address, string subject, string message)
{
string email = "yrshaikh.mail@gmail.com";
string password = "put-your-GMAIL-password-here";
var loginInfo = new NetworkCredential(email, password);
var msg = new MailMessage();
var smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress(address));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}
来源 : 链接
此操作的操作系统 API 函数不可用。