简体   繁体   中英

c# console app to send email automatically

I would like to send an automated email message using c# and outlook. I am confused how to actually send the email, i thought the .Send() method would execute this but nothing happens when i run this and i do not get any compilation errors.

Does anyone know how to activate/execute this code or know somewhere I am messing up. Thank you.

using System;
using System.Management;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Outlook;
using Outlook = Microsoft.Office.Interop.Outlook;


namespace email
{
    class Program
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            SendEmailtoContacts();
        }

        private void SendEmailtoContacts()
        {
            string subjectEmail = "test results ";
            string bodyEmail = "test results";
            Microsoft.Office.Interop.Outlook.Application appp = new  
            Microsoft.Office.Interop.Outlook.Application();
            Microsoft.Office.Interop.Outlook.MAPIFolder sentContacts = 
            appp.ActiveExplorer().Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.O    lDefaultFolders.olFolderContacts);

            foreach (Outlook.ContactItem contact in sentContacts.Items)
            {
                if (contact.Email1Address.Contains("gmail.com"))
                {
                    this.CreateEmailItem(subjectEmail, contact.Email1Address, bodyEmail);
                }
            }
        }

        private void CreateEmailItem(string subjectEmail,string toEmail, string bodyEmail)
        {
            Microsoft.Office.Interop.Outlook.Application app = new  
            Microsoft.Office.Interop.Outlook.Application();
            Microsoft.Office.Interop.Outlook.MailItem eMail = 
            app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

            eMail.Subject = subjectEmail;
            eMail.To = toEmail;
            eMail.Body = bodyEmail;
            eMail.Importance = Outlook.OlImportance.olImportanceLow;
            ((Outlook._MailItem)eMail).Send();
        }

        static void Main(string[] args)
        {

        }
    } 
}

///////////////////////////////////////////////////////////

CORRECT CODE:

using System;
using System.Management;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Outlook;
using Outlook = Microsoft.Office.Interop.Outlook;


namespace email
{
class Program
{

    static void Main(string[] args)
    {

        SendEmailtoContacts();
        CreateEmailItem("yo", "EMAIL@WHATEVER.COM", "yoyoyoyoyo");
    }

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        SendEmailtoContacts();
    }

    private static void SendEmailtoContacts()
    {
        string subjectEmail = "test results ";
        string bodyEmail = "test results";
        Microsoft.Office.Interop.Outlook.Application appp = new  
        Microsoft.Office.Interop.Outlook.Application();
        Microsoft.Office.Interop.Outlook.MAPIFolder sentContacts =     

appp.ActiveExplorer().Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.O lDefaultFolders.olFolderContacts);

        foreach (Outlook.ContactItem contact in sentContacts.Items)
        {
            if (contact.Email1Address.Contains("gmail.com"))
            {
                CreateEmailItem(subjectEmail, contact.Email1Address,
bodyEmail);
            }
        }
    }

    private static void CreateEmailItem(string subjectEmail, string    
 toEmail,     string bodyEmail)
    {
        Microsoft.Office.Interop.Outlook.Application app = new
        Microsoft.Office.Interop.Outlook.Application();
        Microsoft.Office.Interop.Outlook.MailItem eMail =

 app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

        eMail.Subject = subjectEmail;
        eMail.To = toEmail;
        eMail.Body = bodyEmail;
        eMail.Importance = Outlook.OlImportance.olImportanceLow;
        ((Outlook._MailItem)eMail).Send();
    }



} 
}

you could use SMTP to do this

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

static void Main(string[] args)
{
   SendEmail("Lukeriggz@gmail.com", "This is a Test email", "This is where the Body of the Email goes");
}

public static void SendEmail(string sTo, string subject, string body)
{
    var Port = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]);
    using (var client = new SmtpClient(Your EmailHost, Port))
    using (var message = new MailMessage()
    {
        From = new MailAddress(FromEmail),
        Subject = subject,
        Body = body
    })
    {
        message.To.Add(sTo);
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EmailCredential"],
                ConfigurationManager.AppSettings["EmailPassword"]);
        client.EnableSsl = true;
        client.Send(message);
    };
}

if you want a list of contacts to send the same email then create a List<string> and using a foreach loop add them to the message.To.Add(sTo) portion of the code.. pretty straight forward..

if you insist on using Outlook to send emails then looks at this MSDN link

Programmatically Send E-Mail Programmatically

Your question title says "c# console app to send email automatically" but you appear to be using code that was meant for an Outlook AddIn . The addin is meant to call the SendEmail function upon startup of the addin which would execute ThisAddIn_Startup :

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        // this is never executed because it isn't an outlook addin
        SendEmailtoContacts();
    }

    private void SendEmailtoContacts()
    {
       // sends your email... if it actually gets called
    }

Instead try calling that SendEmailtoContacts() function from your Main() because it is a console app and Main() is what is actually executed when you run it:

        static void Main(string[] args)
        {
            SendEmailtoContacts();
        }

For further debugging, as I noted in a comment, because this is outlook interop you should be able to see these operations taking place in an outlook window as they are executed on your local desktop. For example, if you comment out the final ((Outlook._MailItem)eMail).Send(); line and run the program you should be left with an email waiting for you to click the send button after your program terminates.


It looks like you'll also have to modify the method signatures of the other functions to static methods and get rid of the this reference in this.CreateEmailItem?

        public static void SendEmailtoContacts()
        {
            string subjectEmail = "test results ";
            string bodyEmail = "test results";
            Microsoft.Office.Interop.Outlook.Application appp = new  
            Microsoft.Office.Interop.Outlook.Application();
            Microsoft.Office.Interop.Outlook.MAPIFolder sentContacts = 
            appp.ActiveExplorer().Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.O    lDefaultFolders.olFolderContacts);

            foreach (Outlook.ContactItem contact in sentContacts.Items)
            {
                if (contact.Email1Address.Contains("gmail.com"))
                {
                    CreateEmailItem(subjectEmail, contact.Email1Address, bodyEmail);
                }
            }
        }

        public static void CreateEmailItem(string subjectEmail,string toEmail, string bodyEmail)
        {
            Microsoft.Office.Interop.Outlook.Application app = new  
            Microsoft.Office.Interop.Outlook.Application();
            Microsoft.Office.Interop.Outlook.MailItem eMail = 
            app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

            eMail.Subject = subjectEmail;
            eMail.To = toEmail;
            eMail.Body = bodyEmail;
            eMail.Importance = Outlook.OlImportance.olImportanceLow;
            ((Outlook._MailItem)eMail).Send();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM