c# console app to send email automatically - c#

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();
}
}
}

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();
}

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

Related

Update IP Address Text Box If There Is A Change To The Network

I'm trying to do something that is probably very simple, but I can't seem to get it working. I'm writing small app that displays some information including the IP Address. Everything is working perfectly, except that when the IP address changes (Network disconnect, LAN to WiFi, etc), I can't get it to update the text field with a message saying disconnected, or with the new IP Address. I've tried so many things and nothing works. A workaround that I am using is to shut the program down, and then start it immediately.
Here is the workaround code that I am using:
`
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Management.Automation;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;
using System.Xml.Linq;
using System.Net;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Microsoft.TeamFoundation.Common.Internal;
using Microsoft.TeamFoundation.Framework.Common;
namespace JIC_BackgroundInfo
{
public partial class MainWindow : Window
{
private UserPreferenceChangedEventHandler UserPreferenceChanged;
public MainWindow()
{
InitializeComponent();
this.WindowStartupLocation = WindowStartupLocation.Manual;
this.Left = System.Windows.SystemParameters.WorkArea.Width - this.Width;
this.Top = System.Windows.SystemParameters.WorkArea.Height - this.Height;
NetworkChange.NetworkAddressChanged += new
NetworkAddressChangedEventHandler(AddressChangedCallback);
}
static void AddressChangedCallback(object sender, EventArgs e)
{
Process.Start(#"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\JIC_BackgroundInfo.exe");
Thread.Sleep(8500);
Application.Current.Shutdown();
}
`
I tried the following code, along with many other variations, but it just crashes the app:
`
public void AddressChangedCallback(object sender, EventArgs e)
{
using (PowerShell powerShell = PowerShell.Create())
{
try
{
var ps1 = $#"(Get-NetIPAddress -AddressFamily IPv4 -AddressState Preferred -PrefixOrigin Dhcp).IPv4Address";
powerShell.AddScript(ps1);
Collection<PSObject> PSOutput = powerShell.Invoke();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject pSObject in PSOutput)
{
stringBuilder.AppendLine(pSObject.ToString());
}
TxtBoxIPAddress.Text = stringBuilder.ToString();
}
catch { TxtBoxIPAddress.Text = "No Address Found!"; return; }
}
}
`
Look into the ManagementEventWatcher class.
https://learn.microsoft.com/en-us/dotnet/api/system.management.managementeventwatcher?view=dotnet-plat-ext-7.0
You can use it to look for IP Addr changes and then ship those to your window that displays it.
private void AddressChangedCallback(object sender, EventArgs e)
{
Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate
{
using (PowerShell powerShell = PowerShell.Create())
{
try
{
var ps1 = $#"(Get-NetIPAddress -AddressFamily IPv4 -AddressState Preferred -PrefixOrigin Dhcp).IPv4Address";
powerShell.AddScript(ps1);
Collection<PSObject> PSOutput = powerShell.Invoke();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject pSObject in PSOutput)
{
stringBuilder.AppendLine(pSObject.ToString());
}
TxtBoxIPAddress.Text = stringBuilder.ToString();
}
catch { TxtBoxIPAddress.Text = "No Address Found!"; }
}
});
}

Launch a script on remote ssh server using c#

I have a GUI designed on Visual Studio using C#. I am a beginner in C# but good at C++ programming but due to requirements of task, I am designing it in C#. In this GUI, i have a button that connects to remote ssh server and as a trial, i have following commands to run when user presses button1.
client.Connect();
var output = client.RunCommand("echo happy test");
var dltOutput = client.RunCommand("rm /home/helloWorld.txt");
var launchFirst = client.RunCommand("bash /root/first.sh");
client.Disconnect();
Console.WriteLine(output.Result);
The command to delete "helloWorld.txt" in my home folder runs fine but could not running the command to run the shell script "first.sh". I would like to attach complete code below for your reference.
using System;
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.Windows.Forms;
using Renci.SshNet;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
//Connection information
string user = "root";
string pass = "hello123ado";
string host = "192.168.38.50";
int port = 22;
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
Console.WriteLine("Say Button1_Clicked");
using (var client = new SshClient(host,user,pass))
{
client.Connect();
var output = client.RunCommand("echo happy test");
var dltOutput = client.RunCommand("rm /home/helloWorld.txt");
var launchFirst = client.RunCommand("bash /root/first.sh");
client.Disconnect();
Console.WriteLine(output.Result);
}
}
private void Button2_Click(object sender, EventArgs e)
{
Console.WriteLine("Say Button2_Clicked");
}
private void Button3_Click(object sender, EventArgs e)
{
Console.WriteLine("Say Button3_Clicked");
}
}
}

C# MessageBox not working

I've been working on this for a project and the messagebox not showing
Could someone please help me?
using System;
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.Windows.Forms;
using MaterialSkin.Controls;
using MaterialSkin.Animations;
using MaterialSkin;
using System.Web;
using System.Net;
using System.IO;
using System.Management;
using System.Windows;
namespace Liquid_Reborn
{
public partial class Login : MaterialForm
{
public Login()
{
InitializeComponent();
var materialSkinManager = MaterialSkinManager.Instance;
materialSkinManager.AddFormToManage(this);
materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;
materialSkinManager.ColorScheme = new ColorScheme(Primary.LightBlue200, Primary.LightBlue300, Primary.LightBlue300, Accent.LightBlue200, TextShade.WHITE);
}
private void Form1_Load(object sender, EventArgs e)
{
string cpuInfo = string.Empty;
ManagementClass mc = new ManagementClass("win32_processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (cpuInfo == "")
{
//Get only the first CPU's ID
cpuInfo = mo.Properties["processorID"].Value.ToString();
break;
}
var plainTextBytes = Encoding.UTF8.GetBytes(cpuInfo);
String hwid = Convert.ToBase64String(plainTextBytes);
WebClient client = new WebClient();
Stream stream = client.OpenRead("http://techshow.us/liquid/hwid.txt/");
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
if (content.Contains(hwid))
{
}
MessageBox.Show("ok");
}
}
}
}
why doesnt the messagebox display?
ive tried most things and none work
Nothing happens the ui just shows and idk what to do\
please help me i need this for my project
if (cpuInfo == "") will always be true because the value doesn't change after initializing. The loop breaks before the MessageBox code is reached.
Remove break; to allow the code to continue, or
Use continue; instead to skip to the next value in the loop.

IMAP S22.IMAP copy messages between servers

I'm maiking a tool to migrate acoounts between servers.
I'm using S22.IMAP dll, but when I call to Client.CopyMessages(mailIDs, Client2.DefaultMailbox), it
creates the messages in the initial account (duplicate the messages and no copy to the other account server)..
Can anyone help me? thanks
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using S22.Imap;
using System.Net.Mail;
namespace ImapPrueba1
{
public partial class Form1 : Form
{
private static IEnumerable<MailMessage> messages;
private static ImapClient imapClient = null;
private static IEnumerable<string> mailboxes, mailboxes2;
private static IEnumerable<uint> mailIDs;
private static MailMessage mailMessage;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (ImapClient Client = new ImapClient("correo.correo.com", 993,
"correo#correo.es", "xxxxxx", AuthMethod.Login, true))
{
ImapClient Client2 = new ImapClient("correonuevo.correonuevo.com", 993,
"correo#correo.es", "xxxxxx", AuthMethod.Login, true);
mailboxes = Client.ListMailboxes();
string mailbox, mailbox2;
for (int i = 0; i < mailboxes.Count(); i++) {
mailbox = mailboxes.ElementAt(i);
Client.DefaultMailbox = mailbox;
mailIDs = Client.Search(SearchCondition.All());
messages = Client.GetMessages(mailIDs);
//check the folder isn't in the destiny
mailboxes2 = Client2.ListMailboxes();
IEnumerable<string> items = mailboxes2.Where(p => p.Equals(mailbox));
int total = items.Count();
if (total == 0)
{
// set the folder in the destiny
Client2.CreateMailbox(mailbox);
}
Client2.DefaultMailbox = mailbox;
if (mailIDs.Count() > 0)
{
//copy to the destiny
Client.CopyMessages(mailIDs, Client2.DefaultMailbox);
}
}
label1.Text = "cambio";
}
}
}
}

IMAP searchParse exception?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using ActiveUp.Net.Mail;
using ActiveUp.Net.Imap4;
namespace imapClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Imap4Client client = new Imap4Client();
client.ConnectSsl("imap.gmail.com", 993);
MessageBox.Show("connected!");
client.Login("soham.elf", "********");
MessageBox.Show("signed in!");
Mailbox mail = client.SelectMailbox("INBOX");
//exception thrown here
MessageCollection msgs = mail.SearchParse("ALL");
textBox1.Text = msgs.Count.ToString();
}
}
}
Expection:"Index and length must refer to a location within the string.
Parameter name: length"
I am trying to test the IMAP client; I'm just starting with it. I am using mailsystem.NET. What's wrong with my code?
Try use Phrases like that document: http://www.limilabs.com/blog/imap-search-requires-parentheses
private void SearchFromTest()
{
try
{
var _selectedMailBox = "INBOX";
var _searchWithEmailFrom = "email#domain.com";
using (var _clientImap4 = new Imap4Client())
{
_clientImap4.ConnectSsl(_imapServerAddress, _imapPort);
//_clientImap4.Connect(_mailServer.address, _mailServer.port);
_clientImap4.Login(_imapLogin, _imapPassword); // Efetua login e carrega as MailBox da conta.
//_clientImap4.LoginFast(_imapLogin, _imapPassword); // Efetua login e não carrega as MailBox da conta.
var _mailBox = _clientImap4.SelectMailbox(_selectedMailBox);
// A0001 SEARCH CHARSET utf-8 BODY "somestring" OR TO "someone#me.com" FROM "someone#me.com"
var searchPhrase = "CHARSET utf-8 FROM \"" + _searchWithEmailFrom + "\"";
foreach (var messageId in _mailBox.Search(searchPhrase).AsEnumerable())
{
var message = _mailBox.Fetch.Message(messageId);
var _imapMessage = Parser.ParseMessage(message);
}
_clientImap4.Disconnect();
}
Assert.IsTrue(true);
}
catch (Exception e)
{
Assert.Fail("Don't work.", e);
}
}

Categories

Resources