如何在 C# 中向 Outlook 2010 发送电子邮件?

2024-02-19

尽管我的服务器未安装 Outlook 2010 并且位于 Intranet 区域内,是否可以使用 Outlook 发送电子邮件?因为这里的每个人都是通过outlook进行交流的,并且都有一个唯一的outlook账户。我如何从我的应用程序发送电子邮件?我很确定我无法使用以下代码来解决我的问题,请有人帮助我。

code:

// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set HTMLBody. 
//add the body of the email
oMsg.HTMLBody = body;
//Add an attachment.
//String sDisplayName = "MyAttachment";
///int iPosition = (int)oMsg.Body.Length + 1;
//int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
//now attached the file
//Outlook.Attachment oAttach = oMsg.Attachments.Add(@"C:\\fileName.jpg", iAttachType, iPosition, sDisplayName);

//Subject line
oMsg.Subject = subject;
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(address);
oRecip.Resolve();
// Send.
oMsg.Send();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;

这是我在我的项目中使用的示例片段:

using System.Net.Mail;
using System.Net;

private void SendMail( string targetMail, 
                       string shownTargetName, 
                       string[] attachmentNames) {
  var fromAddress = new MailAddress("[email protected] /cdn-cgi/l/email-protection", "MailSendingProgram");
  var toAddress = new MailAddress(targetMail, shownTargetName);
  const string fromPassword = "12345isAbadPassword";
  subject = "Your Subject";
  body = 
        @"
          Here
          you can put in any text
          that will appear in the body
        ";
  var smtp = new SmtpClient {
    Host = "smtp.mailserver.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 }
        ) {
    foreach(string filePath in attachmentNames[]) {
      Attachment attachMail = new Attachment(filePath);
      message.Attachments.Add(attachMail);
    }

    try {
      smtp.Send(message);
      MessageBox.Show("E-Mail sent!");
    } catch {
      MessageBox.Show("Sending failed, check your internet connection!");
    }
  }
}

在此示例中,我包含了使用文件附件所需的所有内容。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 C# 中向 Outlook 2010 发送电子邮件? 的相关文章

随机推荐