Send clipboard content via email using Console Application c# - c#

I have managed to create simple app that will send e-mail with specific text, but I am wondering that is this possible to send the same e-mail, but with content of text being copied into clipboard?
In my oMail.TextBody I would like to paste content of clipboard and e-mail it.
static void Main(string[] server)
{
SmtpMail oMail = new SmtpMail("TryIt");
EASendMail.SmtpClient oSmtp = new EASendMail.SmtpClient();
// Set sender email address
oMail.From = "myEmail";
// Set recipient email address
oMail.To = "myEmail";
// Set email subject
oMail.Subject = "test email from c# project";
// Set email body
oMail.TextBody = "Clipboard content pasted here..."
}
Is there any way to do it? Additionally I am using EASendMail namespace.

In console app, clipboard is accessible in certain thread states, specifically STA.
Take a look at this SO question for explanation.
So, write a static method like this:
static string GetClipboardText()
{
string result = string.Empty;
Thread staThread = new Thread(x =>
{
try
{
result = Clipboard.GetText();
}
catch (Exception ex)
{
result = ex.Message;
}
});
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
return result;
}
and use it in your main method
oMail.TextBody = GetClipboardText();

Related

How to Process NDR emails from Exchange Server in C#?

Currently my application has ability to process incoming emails and bounce then back if it does not match with given criteria in code. However, I want to add up another type of email to Process which are NDR "Non-Delivery Reports" from Microsoft Exchange Server. So my application do not responsd/Bounce back NDR to exchange server which cause a loop between my Mailbox and Exchange Server.
Following method triggers when Invalid doesn't have a specific
private static void ProcessInvidMsgWithoutNo(string sMsgFrom, string sFromEmail, EmailMsg sMsgReceived, EmailMessage message)
{
EmailMsg.MoveToInvalid(message);
sMsgReceived.IsValid = false;
SaveMsgReceived(sMsgReceived, 0, string.Empty);
if (!sFromEmail.Equals(string.Empty))
{
ResponseForInvidMsg(sFromEmail);
}
else
{
curLog.WriteLog(string.Format(CultureInfo.CurrentCulture, MsgEMChecker27, sMsgFrom));
}
}
Following Method triggers to respond incoming Invalid message as stated above.
private static void ResponseForInvidMsg(string sFromEmail)
{
string tErrSubjectMsg = String.Format(CultureInfo.CurrentCulture, "{0}\\Resource\\MsgErrorSubjectAck.html", Entity.GetSetting("DocRootDir"));
StringBuilder htmlText = new StringBuilder();
FileStream fsFile = new FileStream(tErrSubjectMsg, FileMode.Open);
if (fsFile != null)
{
StreamReader reader = new StreamReader(fsFile, Encoding.Default);
string text;
do
{
text = reader.ReadLine();
if ((text != null) && (text != ""))
htmlText.Append(text + "\n");
} while (text != null);
reader.Close();
fsFile.Close();
fsFile = null;
}
else
htmlText.Append("hello");
string tToCustomerSubject = ReplyForInvalid;
string tMessage = htmlText.ToString();
EmailMsg emTo = new EmailMsg(string.Empty, sFromEmail, tToCustomerSubject, tMessage);
emTo.MsgType = EmailMsg.TypeSentCustomer;
emTo.Send(false); //Not save but CC to generic email box
}
Please, help me to find a way where I can stop my code to respond Exchange Server NDR. Thanks
The place to start would be to check the ItemClass of the message see https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-asemail/51d84da6-a2da-41e9-8ca7-eb6c4e72c28d . NDR's, delivery report etc should have a prefix of Report eg
REPORT.IPM.NOTE.NDR Non-delivery report for a standard message.
REPORT.IPM.NOTE.DR Delivery receipt for a standard message.

Sending email with image using C# and Outlook Interop vs copy paste image in email

I have made small C# WFP application that sends emails with embedded images using C# and Outlook Interop. It seems that many mail clients reacts diffently to emails sent from this application compared to manually created emails where images are pasted directly in using CTRL+V.
I have tried to use OutlookSpy to compare the two emails, but I can't see any difference that could cause the different way the emails are being handled.
When an email sent from the C# application is received in an Outlook Application on an Iphone, the images are blank. It works just fine when the image is manually created and images are pasted in using CTRL+V.
1) How do I make sure that the emails sent from my application are handled the same way as when I manually create an email in Outlook and copy an image using CTRL+V?
If I can make this work, then it should be possible to make the images display correctly in Outlook for Iphone.
2) How does outlook handle an image when it is pasted in using CTRL+V? It seems that it uses Cid, the same way as I do in my application, but how does it refer to the image if it is not attached?
Here is the code for the sample application:
private void SendEmailButton_OnClick(object sender, RoutedEventArgs e)
{
SendMail();
}
public void SendMail()
{
var application = GetOutlookApplication();
MailItem newMail = (MailItem)application.CreateItem(OlItemType.olMailItem);
newMail.To = "!!!EnterValidEmailAddress!!!";
newMail.Subject = "Image test";
//Create image as embedded attachment
Attachment attachment1 = newMail.Attachments.Add(#"C:/SomeImage1.png", OlAttachmentType.olByValue);
string imageCid1 = "SomeImage_1";
//The property Accessor to be able to refer to the image from Email HTML Body using CID
attachment1.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageCid1);
//Set property Accesor to hide attachment
attachment1.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x7FFE000B", true);
//Refer the attachment using cid
newMail.HTMLBody = String.Format("<img src=\"cid:{1}\">", "google.dk", imageCid1);
newMail.Save();
newMail.Display();
}
public static OutlookApplication GetOutlookApplication()
{
// Start outlook process if it is not startet already
if (!IsOutlookRunning())
{
using (Process p = new Process())
{
p.StartInfo.FileName = "OUTLOOK.EXE";
p.Start();
if (!p.WaitForInputIdle(10000))
Thread.Sleep(5000);
}
}
// Start the outlook application (API)
OutlookApplication oApp = null;
if (Process.GetProcessesByName("OUTLOOK").Any())
{
try
{
oApp = Marshal.GetActiveObject("Outlook.Application") as OutlookApplication;
}
catch (System.Exception)
{
if (oApp == null)
oApp = new OutlookApplication();
}
return oApp;
}
oApp = new OutlookApplication();
return oApp;
}
private static bool IsOutlookRunning()
{
Process[] p = Process.GetProcessesByName("Outlook");
return p.Length != 0;
}
Make sure that you get a well-formed HTML markup finally. The following line of code just adds the <a> tag to the end of body string:
newMail.HTMLBody += String.Format("<img src=\"cid:{1}\">", "google.dk", imageCid1);
Instead, you need to find a right place for the image between the <body> and </body> tags.

Sending email from Windows Phone 7 application

In my Windows Phone 7 application I want to send an e-mail where the message body should contain the data from my previous page in my application. Previously I just integrated the e-mail facility like this:
private void Image_Email(object sender, RoutedEventArgs e)
{
EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.Subject = "message subject";
emailComposeTask.Body = "message body";
emailComposeTask.To = "recipient#example.com";
emailComposeTask.Cc = "cc#example.com";
emailComposeTask.Bcc = "bcc#example.com";
emailComposeTask.Show();
}
But I was not able to test this in my emulator. Now in the body part I want my data from the previous page. So how to do this?
Updated code:
if (this.NavigationContext.QueryString.ContainsKey("Date_Start"))
{
//if it is available, get parameter value
date = NavigationContext.QueryString["Date_Start"];
datee.Text = date;
}
if (this.NavigationContext.QueryString.ContainsKey("News_Title"))
{
//if it is available, get parameter value
ntitle = NavigationContext.QueryString["News_Title"];
title.Text = ntitle;
}
if (this.NavigationContext.QueryString.ContainsKey("News_Description"))
{
ndes = NavigationContext.QueryString["News_Description"];
description.Text = ndes;
}
Now what do I write in the message body? I am not able to test it as I do not have a device.
Can i pass in the values like this:
emailComposeTask.Body = "title, ndes, date";
I think the code is correct. if you want to pass body from previous page, you need to pass it when page navigation. and set emailComposeTask.Body = yourPassedValue.
like this:
var date;
var title;
var ndes;
emailComposeTask.Body = title + "," + ndes + "," + date;
You need to edit your message body line like this:
emailComposeTask.Body = title+" "+ ndes+" "+ date;
You cannot test sending mail in the emulator since you don't have a proper email account set up. Nor you could set it up in the emulator.
The Body property is a string so you can put inside pretty much anything you want.
Using the following code will only generate a string containing exactly that:
emailComposeTask.Body = "title, ndes, date";
So the result mail will have a body containing "title, ndes, date" as a text. If you want to replace the title with the value from the local variable named title, you need to use the following syntax:
emailComposeTask.Body = string.Format("{0}, {1}, {2}", title, nodes, date);

sending inline MHTML

I was wondering if it is possible through the .NET 2.0 MailMessage object to send an inline MHTML file that is created on the fly.
By inline I mean: It should be sent in a way that the user can see it, once he opens the email, without having to open/download the attachment.
It's a bit tricky, but yes, you can do it. In fact MailMessage class is nothing more than a wrapper above the system's CDO.Message class which can do the trick.
Also you can use AlternateView functionality, it's more simple:
MailMessage mailMessage = new MailMessage("me#me.com"
,"me#me.com"
,"test"
,"");
string ContentId = "wecandoit.jpg";
mailMessage.Body = "<img src=\"cid:" + ContentId + "\"/>";
AlternateView av = AlternateView.CreateAlternateViewFromString(mailMessage.Body
,null
,MediaTypeNames.Text.Html);
LinkedResource lr = new LinkedResource(#"d:\Personal\My Pictures\wecandoit.jpg");
lr.ContentId = ContentId;
lr.ContentType.Name = ContentId;
lr.ContentType.MediaType = "image/jpeg";
av.LinkedResources.Add(lr);
mailMessage.AlternateViews.Add(av);
SmtpClient cl = new SmtpClient();
cl.PickupDirectoryLocation = #"c:\test";
cl.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
cl.Send(mailMessage);
(jdecuyper -- thanks for the plug, as I wrote aspNetEmail).
You can do this with aspNetEmail. You can replace the entire contents of the email message with your MHT.
You can't do this with System.Net.Mail, but if you want to go the commerical route, pop me an email at dave#advancedintellect.com and I'll show you how this can be done.
If you want to go an open source route, there is probably some SMTP code on codeproject that you could modify to do this. Basically, you would inject your contents into the DATA command of the SMTP process.
One thing to note: If your MHT document has embedded scripts, flash, activeX objects or anything that may be blocked by the mail client, it probably won't render the same as what you are seeing in the browser.
Are you trying to add some images to an html email?
To accomplish this you will need to embed the images inside your email. I found a tutorial to accomplish it in a few lines of code. You can also buy the aspnetemail assembly. It has always helped me a lot to send emails with embedded images, they also have an excellent support team if anything goes wrong.
Keep in mind that embedding images makes your email heavier, but nicer :)
It is possible via CDO.Message (it is necessary add to project references COM library "Microsoft CDO for Windows 2000 Library"):
protected bool SendEmail(string emailFrom, string emailTo, string subject, string MHTmessage)
{
string smtpAddress = "smtp.email.com";
try
{
CDO.Message oMessage = new CDO.Message();
// set message
ADODB.Stream oStream = new ADODB.Stream();
oStream.Charset = "ascii";
oStream.Open();
oStream.WriteText(MHTmessage);
oMessage.DataSource.OpenObject(oStream, "_Stream");
// set configuration
ADODB.Fields oFields = oMessage.Configuration.Fields;
oFields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value = CDO.CdoSendUsing.cdoSendUsingPort;
oFields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value = smtpAddress;
oFields.Update();
// set other values
oMessage.MimeFormatted = true;
oMessage.Subject = subject;
oMessage.Sender = emailFrom;
oMessage.To = emailTo;
oMessage.Send();
}
catch (Exception ex)
{
// something wrong
}
}
It is possible via CDO.Message (it is necessary add to project references COM library "Microsoft CDO for Windows 2000 Library"):
protected bool SendEmail(string emailFrom, string emailTo, string subject, string MHTmessage)
{
string smtpAddress = "smtp.email.com";
try
{
CDO.Message oMessage = new CDO.Message();
// set message
ADODB.Stream oStream = new ADODB.Stream();
oStream.Charset = "ascii";
oStream.Open();
oStream.WriteText(MHTmessage);
oMessage.DataSource.OpenObject(oStream, "_Stream");
// set configuration
ADODB.Fields oFields = oMessage.Configuration.Fields;
oFields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value = CDO.CdoSendUsing.cdoSendUsingPort;
oFields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value = smtpAddress;
oFields.Update();
// set other values
oMessage.MimeFormatted = true;
oMessage.Subject = subject;
oMessage.Sender = emailFrom;
oMessage.To = emailTo;
oMessage.Send();
}
catch (Exception ex)
{
// something wrong
}
}

Help! Sending HTML e-mail via C# - Windows Mobile Outlook reads it as gibberish

I have a script that sends an e-mail as both plain text and HTML, and it works fine for most e-mail readers including Outlook and Gmail. However, when reading the message on a Windows Mobile smartphone, the output is:
PCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDMuMiBGaW5hbC8vRU4i Pg0KPEhUTUw+DQo8SEVBRD4NCiAgICA8TUVUQSBIVFRQLUVRVUlWPSJDb250ZW50LVR5cGUi IENPTlRFTlQ9InRleHQvaHRtbDtjaGFyc2V0PWlzby04ODU5LTEiPg0KICAgIDxUSVRMRT5Z b3VyIE1lZ2Fwb255IFBhc3N3b3JkIC0gTWVnYXBvbnkgLSBEaXNjb3ZlciB0aGUgbmV4dCBi aWcgdGhpbmc8L1RJVExFPg0KICAgIDxTVFlMRSBUWVBFPSJ0ZXh0L2NzcyI+DQogICAgICAg IGE6bGluaywgYTp2aXNpdGVkDQogICAgICAgIHsNCiAgICAgICAgICAgIHRleHQtZGVjb3Jh dGlvbjogdW5kZXJsaW5lOw0KICAgICAgICAgICAgY29sb3I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VzcyB5b3Vy IGFjY291bnQuDQogICAgICAgICAgICA8QlI+DQogICAgICAgICAgICA8QlI+DQogICAgICAg ICAgICBUaGFuayB5b3UgZm9yIHlvdXIgc3VwcG9ydCBvZiBNZWdhcG9ueSBhbmQgaW5kZXBl bmRlbnQgbXVzaWMhPEJSPg0KICAgICAgICAgICAgPEJSPg0KICAgICAgICAgICAgU2luY2Vy ZWx5LDxCUj4NCiAgICAgICAgICAgIDxCUj4NCiAgICAgICAgICAgIFRoZSBNZWdhcG9ueSBU ZWFtPEJSPg0KICAgICAgICAgICAgPEJSPg0KICAgICAgICAgICAgPEJSPg0KICAgICAgICA8 L0ZPTlQ+PEZPTlQgU0laRT0iMiIgRkFDRT0iQXJpYWwiPipUaGlzIGlzIGFuIGF1dG9tYXRl ZCBtZXNzYWdlLiBQbGVhc2UgZG8gbm90IHJlcGx5LjwvRk9OVD4NCjwvQk9EWT4NCjwvSFRN TD4NCg==
The correct output should be: Click here to see
The code is:
SmtpClient mC = new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]);
NetworkCredential nC = new NetworkCredential(ConfigurationManager.AppSettings["smtpUsername"], ConfigurationManager.AppSettings["smtpPassword"]);
mC.UseDefaultCredentials = false;
mC.Credentials = nC;
MailAddress mFrom = new MailAddress("noreply#megapony.com", "Megapony");
MailAddress mTo = new MailAddress(forgotpwemail.Text);
MailMessage mMsg = new MailMessage(mFrom, mTo);
mMsg.IsBodyHtml = false;
mMsg.Subject = "Your Megapony Password";
mMsg.Body = getForgotPWBodyPlain(result);
System.Net.Mime.ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(getForgotPWBody(result), mimeType);
mMsg.AlternateViews.Add(alternate);
try
{
mC.Send(mMsg);
pnlpwform.Visible = false;
pnlSuccess.Visible = true;
}
catch (Exception)
{
pnlResponse.Visible = true;
}
mMsg.Dispose();
Please help!
Thanks,
Paul
I would say it's a combination of the content-type and the the image that's causing the issue. The link you provided showed a nice gif with a Megapony logo, yet the content-type is set to text only. Because of this, the bits that make up the gif is being treated as a series of text characters.
This would be a good place to start: http://www.systemnetmail.com/faq/3.1.3.aspx

Categories

Resources