2012-07-04 8 views
12

Deseo usar correos electrónicos enviados a través de Outlook como se describe en here. Funciona bien siempre que ya haya abierto Outlook. Entonces, por ejemplo, si Outlook se minimiza y ejecuto mi código, entonces puedo enviar un correo electrónico sin problemas. Pero si Outlook está cerrado, entonces consigo una excepción:Solo puedo enviar correos electrónicos a través de Outlook si Outlook está abierto

{System.Runtime.InteropServices.COMException (0x80004004): Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT)) 
    at Microsoft.Office.Interop.Outlook._MailItem.get_Recipients() 
    at OutlookExample.Form1.btnSendEmail_Click(Object sender, EventArgs e) in C:\Users\abc\Documents\Visual Studio 2008\Projects\OutlookExample\OutlookExample\Form1.cs:line 28} 

Aquí está el código:

using Outlook = Microsoft.Office.Interop.Outlook; 

... 

private void btnSendEmail_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     Outlook.Application oApp = new Outlook.Application(); 
     Outlook.MailItem oMsg = Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); 
      oMsg.HTMLBody = "Hello, here is your message!"; 
      oMsg.Subject = "This is a test message"; 
      Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients; 
      Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("[email protected]"); 
      oRecip.Resolve(); 
      oMsg.Send(); 
      oRecip = null; 
      oRecips = null; 
      oMsg = null; 
      oApp = null; 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString()); 
    } 
} 

Por qué no funciona?

Editar: Aquí está la solución

using Outlook = Microsoft.Office.Interop.Outlook; 

... 

private void btnSendEmail_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     Outlook.Application oApp = new Outlook.Application(); 

     // These 3 lines solved the problem 
     Outlook.NameSpace ns = oApp.GetNamespace("MAPI"); 
     Outlook.MAPIFolder f = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); 
     System.Threading.Thread.Sleep(5000); // test 

     Outlook.MailItem oMsg = Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); 
      oMsg.HTMLBody = "Hello, here is your message!"; 
      oMsg.Subject = "This is a test message"; 
      Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients; 
      Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("[email protected]"); 
      oRecip.Resolve(); 
      oMsg.Send(); 
      oRecip = null; 
      oRecips = null; 
      oMsg = null; 
      oApp = null; 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString()); 
    } 
} 
+5

no utilice Outlook. En su lugar, use System.Net.Mail. – SLaks

+0

Buena pregunta. Claro, no está conectado todavía? – BugFinder

+0

SLaks, deseo. Lamentablemente, estoy manteniendo el código VB6 y simplemente repliqué el problema en C#. –

Respuesta

12

El siguiente código se ha trabajado de forma fiable durante meses para mí:

  app = new Microsoft.Office.Interop.Outlook.Application(); 
      Microsoft.Office.Interop.Outlook.NameSpace ns = app.GetNamespace("MAPI"); 
      f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox); 
      Thread.Sleep(5000); // a bit of startup grace time. 

Si Outlook estaba abierta se utiliza, si no su abrió . Por supuesto, si su perspectiva requiere que inicie sesión, su código no lo permitirá. Algunos sistemas hacen que sea difícil para usted iniciar sesión automáticamente.

+0

Eso funcionó, gracias. –

10

no me gustaba la idea de utilizar Thread.Sleep durante 5 segundos, por lo que he encontrado otra solución, que trabajó para mí:

Todo lo que necesita es obtener el objeto Inspector de nueva creación

Outlook.Application oApp = new Outlook.Application(); 
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); 
Outlook.Inspector oInspector = oMsg.GetInspector; 

respuesta fue publicado en Google groups originalmente para Outlook 2007 (pero funcionó para mí con Outlook 2010)

+0

Gracias. Gran trabajo :) –

+0

Pero, ¿cómo ayuda ese inspector a ayudar? No está siendo usado en ningún lado o me estoy perdiendo algo? –

+0

Parece que Outlook devuelve Inspector solo después de que se inicializa correctamente. Ese es el truco. No tienes que usarlo. – Woodman

Cuestiones relacionadas