2014-11-27 4 views
4

Я использую Outlook2013, который имеет несколько почтовых ящиков как с обменных, так и с поп-серверов. ([email protected] [обмен по умолчанию], [email protected] [POP], поддержка @ mydomain .com [exchange])Отправка электронной почты с указанной учетной записи Outlook

Я пытаюсь использовать автоматизацию Outlook для отправки электронной почты с помощью учетной записи [email protected]

Проблема, с которой я столкнулся, заключается в том, что приведенный ниже код создает почтовый элемент в списке исходящих сообщений, но поле from - [email protected], а не [email protected] Это предотвращает его отправку.

Я хотел бы изменить адрес с сайта [email protected] Я думал, что, установив свойство Sendusionaccount, сделал это.

Любая помощь очень ценится.

public static string Send_Email_Outlook(string _recipient, string _message, string _subject, string _cc, string _bcc, string accountname) 
    { 
     try 
     { 

      Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application(); 

      // Get the NameSpace and Logon information. 
      Microsoft.Office.Interop.Outlook.NameSpace oNS = oApp.GetNamespace("mapi"); 

      // Log on by using a dialog box to choose the profile. 
      oNS.Logon(Missing.Value, Missing.Value, true, true); 

      // Create a new mail item. 
      Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); 

      // Set the subject. 
      oMsg.Subject = _subject; 

      // Set HTMLBody. 
      oMsg.HTMLBody = _message; 

      oMsg.To = _recipient; 
      oMsg.CC = _cc; 
      oMsg.BCC = _bcc; 


      #region Send via another account 

      if (accountname.Trim().Length != 0) 
      { 
       Microsoft.Office.Interop.Outlook.Accounts accounts = oMsg.Session.Accounts; 
       for (int i = 1; i <= accounts.Count; i++) 
       { 
        string accountfound = accounts[i].DisplayName.ToLower(); 
        if (accountname.ToLower() == accountfound) 
        { 
         oMsg.SendUsingAccount = accounts[i]; // Send using support account 
         Microsoft.Office.Interop.Outlook.Recipient recipient = oMsg.Session.CreateRecipient(accountfound); 
         oMsg.Sender = recipient.AddressEntry; 
         break; 
        } 
       } 
      } 
      #endregion 

      // Send. 
      (oMsg as Microsoft.Office.Interop.Outlook._MailItem).Send(); 

      // Log off. 
      oNS.Logoff(); 

      // Clean up. 
      //oRecip = null; 
      //oRecips = null; 
      oMsg = null; 
      oNS = null; 
      oApp = null; 


     } 

    // Return Error Message 
     catch (Exception e) 
     { 
      return e.Message; 
     } 

     // Default return value. 
     return ""; 

    } 
+0

Попробуйте использовать следующий синтаксис: oMsg.SendUsingAccount = oApp.Session.Accounts.Item (IDX). Другим возможным решением является создание шаблона электронной почты, хранящегося в виде черновика, в котором используется интересующая учетная запись перспективы: для этого потребуется существенное повторное кодирование. С уважением, –

+0

Я исправил его. У меня был почтовый ящик, назначенный мне в обмен, который всегда заставлял его появляться. Как только я не назначил почтовый ящик из моего профиля и повторно добавил, проблема была исправлена. Цените помощь! – Rob

+0

Конечно, добро пожаловать! Удачи вам в вашем проекте. Rgds, –

ответ

6

Да, вы можете использовать SendUsingAccount свойство, чтобы настроить правильную учетную запись, которую необходимо отправить элементы из.

public static Outlook.Account GetAccountForEmailAddress(Outlook.Application application, string smtpAddress) 
{ 

    // Loop over the Accounts collection of the current Outlook session. 
    Outlook.Accounts accounts = application.Session.Accounts; 
    foreach (Outlook.Account account in accounts) 
    { 
     // When the e-mail address matches, return the account. 
     if (account.SmtpAddress == smtpAddress) 
     { 
      return account; 
     } 
    } 
    throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", smtpAddress)); 
} 

public static string Send_Email_Outlook(string _recipient, string _message, string _subject, string _cc, string _bcc, string accountname) 
{ 
    try 
    { 

     Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application(); 

     // Get the NameSpace and Logon information. 
     Microsoft.Office.Interop.Outlook.NameSpace oNS = oApp.GetNamespace("mapi"); 

     // Log on by using a dialog box to choose the profile. 
     oNS.Logon(Missing.Value, Missing.Value, true, true); 

     // Create a new mail item. 
     Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); 

     // Set the subject. 
     oMsg.Subject = _subject; 

     // Set HTMLBody. 
     oMsg.HTMLBody = _message; 

     oMsg.To = _recipient; 
     oMsg.CC = _cc; 
     oMsg.BCC = _bcc; 


     #region Send via another account 

     // Retrieve the account that has the specific SMTP address. 
     Outlook.Account account = GetAccountForEmailAddress(oApp , "[email protected]"); 
     // Use this account to send the e-mail. 
     oMsg.SendUsingAccount = account; 

     // Send. 
     (oMsg as Microsoft.Office.Interop.Outlook._MailItem).Send(); 

     // Log off. 
     oNS.Logoff(); 

     // Clean up. 
     //oRecip = null; 
     //oRecips = null; 
     oMsg = null; 
     oNS = null; 
     oApp = null; 


    } 

// Return Error Message 
    catch (Exception e) 
    { 
     return e.Message; 
    } 

    // Default return value. 
    return ""; 

} 
Смежные вопросы