如何请求操作系统发送带有特定主题、正文和附件的电子邮件?操作系统应该启动预加载字段的默认电子邮件客户端吗?
具体来说,C#.net 中有哪些 API 函数可用?
如何请求操作系统发送带有特定主题、正文和附件的电子邮件?操作系统应该启动预加载字段的默认电子邮件客户端吗?
具体来说,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);
}
这是一个简单的方法,
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);
}
来源:链接
这是一个简单的系统适配器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);
}
不提供用于此的操作系统 API 函数。