I am creating a program that sends a text message and then depending on the reply I want to perform a specific action. Anyways here is my code:
using Microsoft.Office.Interop.Outlook;
using Outlook = Microsoft.Office.Interop.Outlook;
static void Main()
{
var outlook = new Microsoft.Office.Interop.Outlook.Application();
// fire event when a new email arives
outlook.NewMailEx += new ApplicationEvents_11_NewMailExEventHandler(oApp_NewMailEx);
// etc
}
static void oApp_NewMailEx(string EntryIDCollection)
{
var outlook = new Microsoft.Office.Interop.Outlook.Application();
MailItem temp = (MailItem)outlook.Session.GetItemFromID(EntryIDCollection, Missing.Value);
var body = temp.Body; // the body of the email is null! I tried waiting and it is null until I open it...
Console.WriteLine(body);
}
This part is not important but I send the "text message" with this function:
// send text message "att.txt.net only works with at&t phones"
public static int SendEmail(string recipeint = "9546543930#att.txt.net")
{
try
{
// Create the Outlook application by using inline initialization.
Outlook.Application oApp = new Outlook.Application();
//Create the new message by using the simplest approach.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Accounts accounts = oMsg.Session.Accounts;
foreach (Outlook.Account account in accounts)
{
// When the e-mail address matches, send the mail.
if ( account.SmtpAddress.Contains("gmail") )
{
oMsg.SendUsingAccount = account;
break;
}
}
// If you want to, display the message.
oMsg.Display(true); //modal
//Add a recipient.
Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add(recipeint);
oRecip.Resolve();
//Set the basic properties.
oMsg.Subject = "This is the subject of the test message";
oMsg.Body = "This is the text in the message.";
//Add an attachment.
// TODO: change file path where appropriate
//String sSource = "C:\\setupxlg.txt";
//String sDisplayName = "MyFirstAttachment";
//int iPosition = (int)oMsg.Body.Length + 1;
//int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
//Outlook.Attachment oAttach = oMsg.Attachments.Add(sSource, iAttachType, iPosition, sDisplayName);
//Send the message.
oMsg.Save();
oMsg.Send();
//Explicitly release objects.
oRecip = null;
//oAttach = null;
oMsg = null;
oApp = null;
}
// Simple error handler.
catch (System.Exception e)
{
Console.WriteLine("{0} Exception caught: ", e);
}
//Default return value.
return 0;
}
So I am able to send an email with my gmail account and when I reply to the text message the function oApp_NewMailEx gets executed with the id of the new email. I am able to get the subject but the body does not get downloaded until I hover my mouse over the email or open the email. I already waitied 2 minutes on another thread and then tried to see the body and it was still null.
Edit note to make this work I have:
It looks gray out because I did not run outlook as an administrator. If You run outlook as an admin you will be able to update the security settings.
I also imported the Microsoft Outlook 14.0 Object library as a reference.
Once I received the email I called the send and receive method. wait a little and then I was able to read the body.
outlook.Session.SendAndReceive(false);
Related
Using Visual Studio 2022
outlook 365 with IMAP account
VSTO addin.
c#
Event : newmaileX to capture every incoming email. If certain subject, then I enter text into the body. If body is html, I find the tag and insert after. I have create a button on ribbon to test, and the email subject is altered and new text is in the body.
fine so far.
When the newmailex is fired, it runs my code, but sometimes it does not save the changes, and sometimes it does.
Why ?
if I add "mailItem.Save()" this works, but I then get duplicates of the same email. Sometimes upto 10 duplicates. Is this an IMAP thing ? Below is my code.
void NewMail_Event(String entryIDCollection)
{
Outlook.NameSpace outlookNS = this.Application.GetNamespace("MAPI");
Outlook.MailItem mailItem = null;
try
{
string sTag;
string sBody;
int nPos;
sTag = "<table border=\"1\" cellspacing=\"0\"><tr bgcolor=\"#f5e942\"><td><font color=\"#FF0000\" size=\"4\">";
sTag += "This email originated from outside and was not listed in our safe senders list.<br>";
sTag += "DO NOT action, click on any links or open attachments unless you recognise the sender and know the content is safe.";
sTag += "</font></td></tr></table><br>";
string sSubject = null;
string filter = "[EXTERNAL]";
string[] sEmails = entryIDCollection.Split(',');
foreach (string sEmail in sEmails)
{
mailItem = (Outlook.MailItem)outlookNS.GetItemFromID(sEmail, Type.Missing);
if (mailItem.Subject != null)
{
File.AppendAllText("c:\\1data\\desktop\\vstolog.txt", mailItem.Subject + "\r\n");
if (mailItem.Subject.Length >= 10)
{
if (mailItem.Subject.ToUpper().StartsWith(filter))
{
sSubject = mailItem.Subject.Substring(filter.Length, mailItem.Subject.Length - filter.Length);
mailItem.Subject = sSubject;
sBody = mailItem.HTMLBody;
if (sBody.Contains("<body>") || sBody.Contains("<BODY>"))
{
if (sBody.Contains("<BODY>"))
{
sBody = sBody.Replace("<BODY>", "<body>" + sTag);
}
else
{
sBody = sBody.Replace("<body>", "<body>" + sTag);
}
}
else
{
if (sBody.Contains("<body") || sBody.Contains("<BODY"))
{
if (sBody.Contains("<body"))
{
nPos = sBody.IndexOf("<body", 0);
}
else
{
nPos = sBody.IndexOf("<BODY", 0);
}
nPos = sBody.IndexOf(">", nPos);
sBody = sBody.Insert(nPos + 1, sTag);
}
else
{
sBody = sTag + sBody;
}
}
if (mailItem.BodyFormat == OlBodyFormat.olFormatHTML)
{
mailItem.HTMLBody = sBody;
}
else
{
mailItem.Body = sBody;
}
//mailItem.Close(OlInspectorClose.olSave);
}
}
}
Marshal.ReleaseComObject(mailItem);
mailItem = null;
}
}
catch (Exception eX)
{
MessageBox.Show(eX.Message);
}
finally
{
if (mailItem != null) Marshal.ReleaseComObject(mailItem);
mailItem = null;
if (outlookNS != null) Marshal.ReleaseComObject(outlookNS);
outlookNS = null;
}
}
You can find similar issues described in case of IMAP profiles configured in Outlook, see IMAP Sent Messages are duplicated and unread in Sent Items folder for more information.
I suppose you are handling the NewMailEx event of the Application class, not the NewMail one. There are several aspects in the code:
string[] sEmails = entryIDCollection.Split(',');
The EntryIDsCollection string contains the Entry ID that corresponds to that item. Note that this behavior has changed from earlier versions of the event when the EntryIDCollection contained a list of comma-delimited Entry IDs of all the items received in the Inbox since the last time the event was fired.
However, depending on the setup on the client computer, after a new message arrives in the Inbox, processes like spam filtering and client rules that move the new message from the Inbox to another folder can occur asynchronously. You should not assume that after these events fire, you'll always get a one-item increase in the number of items in the Inbox.
As a possible workaround you may try to handle the ItemAdd event on the target folder instead.
using Outlook = Microsoft.Office.Interop.Outlook;
I'm able to sending the mail using above Outlook dll but I want to send a mail which I configured in the the logic "FROM' MailID only
I'm trying to sending the mail which I configured mail only "FROM", but while I'm sending the mail I'm getting error
Outlook does not recognize one or more names
where did I make the mistake and how to send the logically written FROM MailID only?
public int sendMFSwitchMail(MAEEmail mAEEmail , string data)
{
try
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
//string pathfilecontent = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"\payment_failed_mail.html";
string pathfilecontent = Server.MapPath(#"\payment_failed_mail.html");
string contentmailstr = "";
//if (string.IsNullOrEmpty(mAEEmail.Body))
// contentmailstr = File.ReadAllText(pathfilecontent);
//else
// contentmailstr = mAEEmail.Body;
contentmailstr = File.ReadAllText(pathfilecontent);
contentmailstr = contentmailstr.Replace("Full_Name", data);
//contentmailstr = contentmailstr.Replace("Existing_Baskets_Constituents", oldfund);
//contentmailstr = contentmailstr.Replace("New_Baskets_Constituents", newfund);
oMsg.HTMLBody = contentmailstr;// sb.ToString();
//oMsg.HTMLBody = mAEEmail.Body;
//Subject line
oMsg.Subject = mAEEmail.Subject;
//if (!string.IsNullOrEmpty(mAEEmail.BCC))
// oMsg.BCC = mAEEmail.BCC;
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// {"Outlook does not recognize one or more names. "}
oRecips.Add(mAEEmail.From);//from mail:abc#cyient.com[outlook, programmatically configured mailid]
oRecips.Add(mAEEmail.Password);
//Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(mAEEmail.To); // to mail : a#gmail.com
oRecip.Resolve();
// Send.
//Console.WriteLine("Sending email...");
oMsg.Send();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
//return 1;
}
catch(Exception ex)
{
//MessageBox.Show("Error is :" + ex.Message.ToString());
//throw;
Response.Write("Error is :" + ex.Message.ToString());
//loggingService.Log("Error is:" + ex.Message.ToString());
}
return 1;
}
You are adding the sender as one of the recipients, that does not make much sense. The error you are getting means the name cannot be resolved, which means it is not an SMTP address or a name in your contacts. Are you sure you the value if just an SMTP address?
To specify the sender, you need to either set the MailItem.SendUsingAccount property to one of the Account objects from the Application.Session.Accounts collection, or, in case of Exchange, set the MailItem.SentOnBehalfOfName property to the name (not address) of another Exchange user on whose behalf you are allowed to send.
I am uploading a database every day. Whenever the upload is done, the program should automatically send an e-mail to certain recipients.
My Outlook is 2013 Professional Plus.
using Microsoft.Office.Interop.Outlook;
using OutlookApp = Microsoft.Office.Interop.Outlook.Application;
OutlookApp outlookApp = new OutlookApp();
// Create a new mail item.
//Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
MailItem mailItem = outlookApp.CreateItem(OlItemType.olMailItem);
// Set HTMLBody.
//add the body of the email
mailItem.HTMLBody = "Prezados, a base " + Produto + " foi atualizada.<br>"
+ "Data e hora local do upload: " + localDate.ToString("en-GB") +" " + localDate.Kind + "<br>"
+ "Email gerado automaticamente."
;
//Subject line
//oMsg.Subject =
mailItem.Subject = "Atualização diária da base " + Produto
The code Works so far. Beyond this, i don't know how to properly structure it or call the functions to send an email to the desired recipients.
The remaining code you will see in the next panel uses a structure that i previously scrapped, that worked with Outlook 2010. I need to adapt this next part to function with my new code compatible with Outlook 2013, but i have no idea how to do it
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("email_template#x.com");
Outlook.Recipient oRecip1 = (Outlook.Recipient)oRecips.Add("email_template#x.com");
Outlook.Recipient oRecip2 = (Outlook.Recipient)oRecips.Add("email_template#x.com");
Outlook.Recipient oRecip3 = (Outlook.Recipient)oRecips.Add("email_template#x.com");
oRecip.Resolve();
oRecip1.Resolve();
oRecip2.Resolve();
oRecip3.Resolve();
// Send.
oMsg.Send();
// Clean up.
oRecip = null;
oRecip1 = null;
oRecip2 = null;
oRecip3 = null;
oRecips = null;
oMsg = null;
oApp = null;
I have the following code:
string imageSrc = "C:\\Documents and Settings\\menonsu\\Desktop\\screenScrapper\\Bitmap1.bmp";
oMsg.HTMLBody = "<HTML><BODY><img src = \" cid:Bitmap1.bmp#embed \"/><br><font size=\"2\" face=\"Courier New\">" + introText + "</font>" + body + "<font size=\"2\" face=\"Courier New\">" + conclText + "</font>" + " </BODY></HTML>";
Microsoft.Office.Interop.Outlook.Attachment attc = oMsg.Attachments.Add(imageSrc, Microsoft.Office.Interop.Outlook.OlAttachmentType.olEmbeddeditem, null, "");
attc.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", "Bitmap1.bmp#EMBED");
//Send the message.
oMsg.Save();
For some reason the email is just showing an x when i try to run this code...anyone know why?
The following is working code with two ways of achieving this:
using System;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Method1();
Method2();
}
public static void Method1()
{
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = "This is the subject";
mailItem.To = "john#example.com";
string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed
var attachments = mailItem.Attachments;
var attachment = attachments.Add(imageSrc);
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F", "image/jpeg");
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "myident"); // Image identifier found in the HTML code right after cid. Can be anything.
mailItem.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8514000B", true);
// Set body format to HTML
mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
string msgHTMLBody = "<html><head></head><body>Hello,<br><br>This is a working example of embedding an image unsing C#:<br><br><img align=\"baseline\" border=\"1\" hspace=\"0\" src=\"cid:myident\" width=\"\" 600=\"\" hold=\" /> \"></img><br><br>Regards,<br>Tarik Hoshan</body></html>";
mailItem.HTMLBody = msgHTMLBody;
mailItem.Send();
}
public static void Method2()
{
// Create the Outlook application.
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
//Add an attachment.
String attachmentDisplayName = "MyAttachment";
// Attach the file to be embedded
string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed
Outlook.Attachment oAttach = mailItem.Attachments.Add(imageSrc, Outlook.OlAttachmentType.olByValue, null, attachmentDisplayName);
mailItem.Subject = "Sending an embedded image";
string imageContentid = "someimage.jpg"; // Content ID can be anything. It is referenced in the HTML body
oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageContentid);
mailItem.HTMLBody = String.Format(
"<body>Hello,<br><br>This is an example of an embedded image:<br><br><img src=\"cid:{0}\"><br><br>Regards,<br>Tarik</body>",
imageContentid);
// Add recipient
Outlook.Recipient recipient = mailItem.Recipients.Add("john#example.com");
recipient.Resolve();
// Send.
mailItem.Send();
}
}
}
From what I can tell, you are not setting the content id properly. Try to change the code to the following:
attc.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F", "image/bmp");
attc.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "Bitmap1.bmp#EMBED");
I have done this before a little differently. I embedded images in some emails that I had to send from my web app using an 'alternate view' in the system.net.mail
System.Net.Mail.LinkedResource theContent = new System.Net.Mail.LinkedResource({path to image});
theContent.ContentID = "TheContent";
String altViewString = anEmail.Body.replace("{original imageSource i.e. '../Images/someimage.gif'}","cid:TheContent");
System.Net.Mail.AlternateView altView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(altViewString, Nothing, System.Net.Mime.MediaTypeNames.Text.Html);
altView.LinkedResources.add(theContent);
anEmail.Message.AlternateViews.Add(altView);
Here's a simple solution:
private static void insertPictureAsLink(Outlook.MailItem mail, String imagePath, String URI)
{
mail.BodyFormat = OlBodyFormat.olFormatHTML;
mail.HTMLBody += String.Format("<body></body>", imagePath, URI);
mail.Display(false);
}
I want to send an email as pdf attachment without save/export it somewhere from the telerik report viewer but I cant find a way.
Also when I am on debug mode and view the designer I see this button and on the properties doesn't have anything for emails.
When I run the project on the browser this button doesn't show.
Anyone knows why?
I tried to make a button with this code but I couldn't convert the report to pdf from my code .
protected void RadButton1_Click(object sender, EventArgs e)
{
string type = Request.Params["type"];
string no = Request.Params["no"];
string stat = Request.Params["stat"];
//Session["compcode"] = Request.Params["compcode"];
var instanceReportSource = new Telerik.Reporting.InstanceReportSource();
instanceReportSource.ReportDocument = new Reports.Report1();
instanceReportSource.Parameters.Add("docno", no);
instanceReportSource.Parameters.Add("doctype", type);
instanceReportSource.Parameters.Add("docstat", stat);
try
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set HTMLBody.
//add the body of the email
oMsg.HTMLBody = "Hello, Jawed your message body will go here!!";
//Add an attachment.
String sDisplayName = "MyAttachment";
int iPosition = (int)oMsg.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
//now attached the file
Outlook.Attachment oAttach = oMsg.Attachments.Add("here must be the report as pdf", iAttachType, iPosition, sDisplayName);
//Subject line
oMsg.Subject = "Your Subject will go here.";
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("xxxxx#gmail.com");
oRecip.Resolve();
// Send.
oMsg.Send();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}//end of try block
catch (Exception ex)
{
string ep = ex.ToString();
}//end of catch
}
The button you have circled above is to show/hide the parameter area of the report viewer. If you look at there documentation for the Report Viewer it will explain how to customize the tool bar, which would allow you to add an email button onto the toolbar. Then in your code behind you will have to render the report in some format, probably pdf, into a memory stream and then attach that to your email engine. They have an old example of how to email a report here: http://www.telerik.com/blogs/send-telerik-report-as-email-attachment.