How can I send console output to my email? [duplicate] - c#

This question already has answers here:
send email in c#
(7 answers)
Closed 3 years ago.
I want to get help with how to send the console output via email on a click button function in my program.
The variable textBox2.Text contains the text that is being printed out to the console and I want this text to be send automatically on the (button1_Click_1) function.
I have found some solutions on somewhat similar questions but none of them seem to work, I hope I can find a solution here.
My code:
private void textBox2_TextChanged(object sender, EventArgs e)
{
Console.WriteLine(textBox2);
}
private void button1_Click_1(object sender, EventArgs e)
{
//Sending email function with the console output that is being printed from (textBox2.Text) should be here.
Taskbar.Show();
System.Windows.Forms.Application.Exit();
}

Microsoft recommends that MailKit and MimeKit libraries be used for sending emails from C# applications.
Here is the working code snippet in C# for sending an email:
// File name: SendMail.cs
using System;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;
namespace SendMail {
class Program
{
public static void Main (string[] args) {
using (var client = new SmtpClient ()) {
// Connect to the email service (Accept ssl certificate)
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
client.Connect ("smtp.friends.com", 587, false);
// Optional step: Send user id, password, if the server requires authentication
client.Authenticate ("emailID", "emailPassword");
// Construct the email message
var message = new MimeMessage();
message.From.Add (new MailboxAddress ("Sender's Name", "sender-email#example.com"));
message.To.Add (new MailboxAddress ("Receiver's Name", "receiver-email#example.com"));
message.Subject = "Automatic email from the application";
message.Body = new TextPart ("plain") { Text = #"Hello Customer, Happy new year!"};
// Send the email
client.Send (message);
// Close the connection with the email server
client.Disconnect (true);
}
}
}
}
More information:
https://github.com/jstedfast/MailKit

Related

Send an Email on IOS Platform

I'm trying to add email capability to my IOS project made with Xamarin Forms. I'm using DependencyService to implement the email function and my IOS code is as follows:
public void SendEmail(string[] recipients, string subject, string body, string filePath, string fileName)
{
MFMailComposeViewController mailController;
if (MFMailComposeViewController.CanSendMail)
{
mailController = new MFMailComposeViewController();
mailController.SetToRecipients(recipients);
mailController.SetSubject(subject);
mailController.SetMessageBody(body, false);
mailController.AddAttachmentData(NSData.FromFile(filePath), "application/pdf", fileName);
mailController.Finished += (object s, MFComposeResultEventArgs args) =>
{
Console.WriteLine(args.Result.ToString());
args.Controller.DismissViewController(true, null);
};
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailController, true, null);
}
}
but when I test the implementation, nothing happens no errors or anything. I can continue to use the app as normal after the failed attempt to email. I understand this question has been asked here and here but I have already enabled an email account on my testing iPad's default mail app and have removed all instances of DisplayActionSheet in my PCL implementation.

ASP.net mvc5 sending email every 7 day?

I'm working on a small project of mine and I'm not sure if what I am trying to do is possible on a web based solution.
And right now it's setup like this, a user post something and that date he posted in the database. What I want to do is if the user doesn't post another thing within 7 days I want to send them an email saying they are "late" or something similar to that.
I know how to send a email in asp.net as my user can request a new password / they need to verify their email. I just don't know how to set it up like I want above ( IF that even is possible )
You need a separate process that checks for, and then sends, the emails. You won't be able to do it in the web application itself, but some kind of service would do it.
This service would just need to periodically check your database for users and the last date they posted. If it's more than 7 days, send that email off.
Remember to record that the email has been sent and check this when determining what emails to send, otherwise you'll get an email sent every time the service checks the database, which might frustrate the user a bit!
sending email in asp is simple. its a code i did before that check if you want to send a file too:
for working with time you have to work with timeSpan and dateTime
its from example in stackoverflow:
Assuming StartDate and EndDate are of type DateTime:
(EndDate - StartDate).TotalDays
you have to check if this value is bigger than 7
so code for sending mail is like below but you have to optimize it for your own:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
MailMessage mail = new MailMessage();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
lblmessage.Text ="";
mail.To.Add(txtto.Text.Trim());
mail.From = new MailAddress(txtfrom.Text.Trim());
mail.Subject = txtsubject.Text.Trim();
mail.Body = txtbody.Text.Trim();
mail.IsBodyHtml = true;
if (uploader.HasFile)
{
string filename = uploader.PostedFile.FileName;
string filepath=Server.MapPath("uploads//"+filename);
uploader.SaveAs(filepath);
Attachment attach = new Attachment(filepath);
attach.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
mail.Attachments.Add(attach);
}
SmtpClient client = new SmtpClient();
client.Host = "mail.youdomain.com";
client.Credentials = new System.Net.NetworkCredential("email username=info#yourdomain.com", "email passowrd");
client.Send(mail);
lblmessage.Text = "sent with success";
}
catch (Exception ex)
{
lblmessage.Text = ex.Message;
}
}
}

How can I know if my sent email was successful [duplicate]

This question already has answers here:
How to check if the mail has been sent successfully
(8 answers)
Closed 8 years ago.
I am trying to develop an application which sends email to multiple recepients.
I am reading all the mail addresses from a text file line by line.But I am wondering ..for example I have 50 mail addresses in my list and something went wrong with the number 45.
How can I inform the user about about it and is it possibble sending the rest of the list?
private void Senmail(IEnumerable<string> list)
{
var mes = new MailMessage {From = new MailAddress(_uname.Trim())};
var col = new MailAddressCollection();
foreach (string adres in list)
{
col.Add(adres);
}
for (int i = 0; i < GetList().Count(); i++)
{
mes.To.Add(col[i].Address);
}
mes.Subject = txtbody.Text;
mes.Body = txtmail.Text;
mes.Attachments.Add(new Attachment(_filename));
var client = new SmtpClient
{
Port = 587,
Host = "smtp.gmail.com",
EnableSsl = true,
Timeout = 5000,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(_uname, _pass),
};
object userState = mes;
client.SendAsync(mes,userState);
client.SendCompleted += client_SendCompleted;
MessageBox.Show("ok");
}
void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error!=null)
{
//
}
}
Since you're using Gmail your options are very limited. At best you will get an exception if the SMTP host cannot be reached, but if you get a 200 response then you have technically fulfilled the end of your delivery contract and any subsequent response will be delivered after the fact (email does not exist, for example).
You might find some extra options under MailMessage's DeliveryNotificationOptions property and handle exceptions, but these are limited and really don't provide what I believe you are looking for.

How do you send an RichText Document as the body of an e-mail programatically using SmtpClient with .net

I am writing a WPF .net app to send an e-mail to several people.
I've got the program working so that it sends plain text e-mails using the code below:
private void OnSendEmails(object sender, RoutedEventArgs e)
{
using (SmtpClient smtpClient = new SmtpClient("<mySMTPserver>", <somePort>))
{
smtpClient.Timeout = 10000;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("<myusername>", "<mypassword");
foreach (string address in Addresses)
{
try
{
Console.Out.WriteLine("Sending e-mail to: {0}", address);
smtpClient.Send(Sender, address, Subject, Body);
Console.Out.WriteLine("Sent e-mail to: {0}", address);
}
catch (Exception ex)
{
Console.Out.WriteLine("Exception thrown while sending to : {0}\r\n\r\n{1}", address, ex);
}
Console.Out.WriteLine("Sleeping");
Thread.Sleep(Seconds * 1000);
Console.Out.WriteLine("Done Sleeping");
}
}
}
I would like to send several e-mails out to a select group of people to advertise an app that I wrote. However, I want to send them something other than plain text. I can populate a RichTextBox with the content I wish to send, however, I don't know how to send it since SmtpClient just takes a 'string' to represent the body of the e-mail.
So the question is, how do I send the RichTextBox.Document as the Body of my e-mail using .net and SmptClient?
The document itself will contain images, text, and some links that are associated with icons.
try to create an object of type MailMessage:
var msg = new MailMessage(...);
then you can set this property:
msg.IsBodyHtml = true;
and the message body will be rendered in HTML format.
I am not totally sure the RichTextBox would pass HTML or probably RTF which is slightly different, it could be you should convert RTF into HTML with an helper method before assigning the content to msg.Body.

using c# .net libraries to check for IMAP messages from gmail servers [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Does anyone have any sample code in that makes use of the .Net framework that connects to googlemail servers via IMAP SSL to check for new emails?
I'd recommend looking at MailKit as it is probably the most robust mail library out there and it's Open Source (MIT).
One of the awesome things about MailKit is that all network APIs are cancelable (something I haven't seen available in any other IMAP library).
It's also the only library that I know of that supports threading of messages.
using System;
using System.Net;
using System.Threading;
using MailKit.Net.Imap;
using MailKit.Search;
using MailKit;
using MimeKit;
namespace TestClient {
class Program
{
public static void Main (string[] args)
{
using (var client = new ImapClient ()) {
using (var cancel = new CancellationTokenSource ()) {
client.Connect ("imap.gmail.com", 993, true, cancel.Token);
// If you want to disable an authentication mechanism,
// you can do so by removing the mechanism like this:
client.AuthenticationMechanisms.Remove ("XOAUTH");
client.Authenticate ("joey", "password", cancel.Token);
// The Inbox folder is always available...
var inbox = client.Inbox;
inbox.Open (FolderAccess.ReadOnly, cancel.Token);
Console.WriteLine ("Total messages: {0}", inbox.Count);
Console.WriteLine ("Recent messages: {0}", inbox.Recent);
// download each message based on the message index
for (int i = 0; i < inbox.Count; i++) {
var message = inbox.GetMessage (i, cancel.Token);
Console.WriteLine ("Subject: {0}", message.Subject);
}
// let's try searching for some messages...
var query = SearchQuery.DeliveredAfter (DateTime.Parse ("2013-01-12"))
.And (SearchQuery.SubjectContains ("MailKit"))
.And (SearchQuery.Seen);
foreach (var uid in inbox.Search (query, cancel.Token)) {
var message = inbox.GetMessage (uid, cancel.Token);
Console.WriteLine ("[match] {0}: {1}", uid, message.Subject);
}
client.Disconnect (true, cancel.Token);
}
}
}
}
}
The URL listed here might be of interest to you
http://www.codeplex.com/InterIMAP
which was extension to
http://www.codeproject.com/KB/IP/imaplibrary.aspx?fid=91819&df=90&mpp=25&noise=5&sort=Position&view=Quick&fr=26&select=2562067#xx2562067xx
As the author of the above project i can say that yes it does support SSL.
I am currently working on a new version of the library that will be completely asynchronous to increase the speed with which it can interact with IMAP servers.
That code, while not complete, can be downloaded, along with the original synchronous library (which also supports SSL), from the code plex site linked to above.
Cross posted from the other similar question. See what happens when they get so similar?
I've been searching for an IMAP solution for a while now, and after trying quite a few, I'm going with AE.Net.Mail.
There is no documentation, which I consider a downside, but I was able to whip this up by looking at the source code (yay for open source!) and using Intellisense. The below code connects specifically to Gmail's IMAP server:
// Connect to the IMAP server. The 'true' parameter specifies to use SSL
// which is important (for Gmail at least)
ImapClient ic = new ImapClient("imap.gmail.com", "name#gmail.com", "pass",
ImapClient.AuthMethods.Login, 993, true);
// Select a mailbox. Case-insensitive
ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());
// Get the first *11* messages. 0 is the first message;
// and it also includes the 10th message, which is really the eleventh ;)
// MailMessage represents, well, a message in your mailbox
MailMessage[] mm = ic.GetMessages(0, 10);
foreach (MailMessage m in mm)
{
Console.WriteLine(m.Subject);
}
// Probably wiser to use a using statement
ic.Dispose();
I'm not affiliated with this library or anything, but I've found it very fast and stable.
Lumisoft.net has both IMAP client and server code that you can use.
I've used it to download email from Gmail. The object model isn't the best, but it is workable, and seems to be rather flexible and stable.
Here is the partial result of my spike to use it. It fetches the first 10 headers with envelopes, and then fetches the full message:
using (var client = new IMAP_Client())
{
client.Connect(_hostname, _port, _useSsl);
client.Authenticate(_username, _password);
client.SelectFolder("INBOX");
var sequence = new IMAP_SequenceSet();
sequence.Parse("0:10");
var fetchItems = client.FetchMessages(sequence, IMAP_FetchItem_Flags.Envelope | IMAP_FetchItlags.UID,
false, true);
foreach (var fetchItem in fetchItems)
{
Console.Out.WriteLine("message.UID = {0}", fetchItem.UID);
Console.Out.WriteLine("message.Envelope.From = {0}", fetchItem.Envelope.From);
Console.Out.WriteLine("message.Envelope.To = {0}", fetchItem.Envelope.To);
Console.Out.WriteLine("message.Envelope.Subject = {0}", fetchItem.Envelope.Subject);
Console.Out.WriteLine("message.Envelope.MessageID = {0}", fetchItem.Envelope.MessageID);
}
Console.Out.WriteLine("Fetching bodies");
foreach (var fetchItem in client.FetchMessages(sequence, IMAP_FetchItem_Flags.All, false, true)
{
var email = LumiSoft.Net.Mail.Mail_Message.ParseFromByte(fetchItem.MessageData);
Console.Out.WriteLine("email.BodyText = {0}", email.BodyText);
}
}
There is no .NET framework support for IMAP. You'll need to use some 3rd party component.
Try Mail.dll email component, it's very affordable and easy to use, it also supports SSL:
using(Imap imap = new Imap())
{
imap.ConnectSSL("imap.company.com");
imap.Login("user", "password");
imap.SelectInbox();
List<long> uids = imap.Search(Flag.Unseen);
foreach (long uid in uids)
{
string eml = imap.GetMessageByUID(uid);
IMail message = new MailBuilder()
.CreateFromEml(eml);
Console.WriteLine(message.Subject);
Console.WriteLine(message.Text);
}
imap.Close(true);
}
Please note that this is a commercial product I've created.
You can download it here: https://www.limilabs.com/mail.
MailSystem.NET contains all your need for IMAP4. It's free & open source.
(I'm involved in the project)
the source to the ssl version of this is here: http://atmospherian.wordpress.com/downloads/
Another alternative: HigLabo
https://higlabo.codeplex.com/documentation
Good discussion: https://higlabo.codeplex.com/discussions/479250
//====Imap sample================================//
//You can set default value by Default property
ImapClient.Default.UserName = "your server name";
ImapClient cl = new ImapClient("your server name");
cl.UserName = "your name";
cl.Password = "pass";
cl.Ssl = false;
if (cl.Authenticate() == true)
{
Int32 MailIndex = 1;
//Get all folder
List<ImapFolder> l = cl.GetAllFolders();
ImapFolder rFolder = cl.SelectFolder("INBOX");
MailMessage mg = cl.GetMessage(MailIndex);
}
//Delete selected mail from mailbox
ImapClient pop = new ImapClient("server name", 110, "user name", "pass");
pop.AuthenticateMode = Pop3AuthenticateMode.Pop;
Int64[] DeleteIndexList = new.....//It depend on your needs
cl.DeleteEMail(DeleteIndexList);
//Get unread message list from GMail
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
//Select folder
ImapFolder folder = cl.SelectFolder("[Gmail]/All Mail");
//Search Unread
SearchResult list = cl.ExecuteSearch("UNSEEN UNDELETED");
//Get all unread mail
for (int i = 0; i < list.MailIndexList.Count; i++)
{
mg = cl.GetMessage(list.MailIndexList[i]);
}
}
//Change mail read state as read
cl.ExecuteStore(1, StoreItem.FlagsReplace, "UNSEEN")
}
//Create draft mail to mailbox
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
var smg = new SmtpMessage("from mail address", "to mail addres list"
, "cc mail address list", "This is a test mail.", "Hi.It is my draft mail");
cl.ExecuteAppend("GMail/Drafts", smg.GetDataText(), "\\Draft", DateTimeOffset.Now);
}
}
//Idle
using (var cl = new ImapClient("imap.gmail.com", 993, "user name", "pass"))
{
cl.Ssl = true;
cl.ReceiveTimeout = 10 * 60 * 1000;//10 minute
if (cl.Authenticate() == true)
{
var l = cl.GetAllFolders();
ImapFolder r = cl.SelectFolder("INBOX");
//You must dispose ImapIdleCommand object
using (var cm = cl.CreateImapIdleCommand()) Caution! Ensure dispose command object
{
//This handler is invoked when you receive a mesage from server
cm.MessageReceived += (Object o, ImapIdleCommandMessageReceivedEventArgs e) =>
{
foreach (var mg in e.MessageList)
{
String text = String.Format("Type is {0} Number is {1}", mg.MessageType, mg.Number);
Console.WriteLine(text);
}
};
cl.ExecuteIdle(cm);
while (true)
{
var line = Console.ReadLine();
if (line == "done")
{
cl.ExecuteDone(cm);
break;
}
}
}
}
}
LumiSoft.ee - works great, fairly easy. Compiles with .NET 4.0.
Here are the required links to their lib and examples.
Downloads Main:
http://www.lumisoft.ee/lsWWW/Download/Downloads/
Code Examples:
are located here: ...lsWWW/Download/Downloads/Examples/
.NET:
are located here: ...lsWWW/Download/Downloads/Net/
I am putting a SIMPLE sample up using their lib on codeplex (IMAPClientLumiSoft.codeplex.com). You must get their libraries directly from their site. I am not including them because I don't maintain their code nor do I have any rights to the code. Go to the links above and download it directly. I set LumiSoft project properties in my VS2010 to build all of it in .NET 4.0 which it did with no errors.
Their samples are fairly complex and maybe even overly tight coding when just an example. Although I expect that these are aimed at advanced level developers in general.
Their project worked with minor tweaks. The tweaks: Their IMAP Client Winform example is set in the project properties as "Release" which prevents VS from breaking on debug points. You must use the solution "Configuration Manager" to set the project to "Active(Debug)" for breakpoints to work. Their examples use anonymous methods for event handlers which is great tight coding... not real good as a teaching tool. My project uses "named" event method handlers so you can set breakpoints inside the handlers. However theirs is an excellent way to handle inline code. They might have used the newer Lambda methods available since .NET 3.0 but did not and I didn't try to convert them.
From their samples I simplified the IMAP client to bare minimum.

Categories