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 followed this guide to try and embed 2 images on Emails
this is my code written in C# for a console application:
the ExecuteSendMailEx procedure:
public void ExecuteSendMailEx(AccesBase accesBase, string From, string Subjet, bool Format, string EmailLogoHeader, string EmailLogoFooter, string ReplyTo, string ReturnPath, string BodyHtml, string BodyText, string Destinataire, string IdLangage, string CopieCachee, string PJ, string SMTP, string SMTPPORT, string SMTPLOGIN, string SMTPPWD, ref int RTN)
{
try
{
Log.Information("ENVOI_Constructor ExecuteSendMailEx has begun");
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(From));
email.To.Add(MailboxAddress.Parse(Destinataire));
email.ReplyTo.Add(MailboxAddress.Parse(ReplyTo));
if (!string.IsNullOrEmpty(CopieCachee))
email.Bcc.Add(MailboxAddress.Parse(CopieCachee));
email.Subject = Subjet;
email.Sender = (MailboxAddress.Parse(SMTPLOGIN));
var currentDirectory = Directory.GetCurrentDirectory();
var parentDirectory = Directory.GetParent(currentDirectory).FullName;
var filesDirectory = parentDirectory + "\\Files";
var builder = new BodyBuilder();
if (EmailLogoHeader != "" && EmailLogoFooter != "")
{
var imageHead = builder.LinkedResources.Add(filesDirectory + "\\" + EmailLogoHeader);
imageHead.ContentId = MimeUtils.GenerateMessageId();
var imageFoot = builder.LinkedResources.Add(filesDirectory + "\\" + EmailLogoFooter);
imageFoot.ContentId = MimeUtils.GenerateMessageId();
builder.HtmlBody = string.Format(#"<img src='cid:{0}'><br>{1}<br><img src='cid:{2} '>", imageHead.ContentId, BodyHtml, imageFoot.ContentId);
}
else if (EmailLogoFooter != "" && EmailLogoHeader == "")
{
var imageFoot = builder.LinkedResources.Add(filesDirectory + "\\" + EmailLogoFooter);
imageFoot.ContentId = MimeUtils.GenerateMessageId();
builder.HtmlBody = string.Format(#"{0}<br><img src='cid={1}'>", BodyHtml, imageFoot.ContentId);
}
else if (EmailLogoHeader != "" && EmailLogoFooter == "")
{
var imageHead = builder.LinkedResources.Add(filesDirectory+"\\" + EmailLogoHeader);
imageHead.ContentId = MimeUtils.GenerateMessageId();
builder.HtmlBody = string.Format(#"<img src='cid:{0}'><br>{1}", imageHead.ContentId, BodyHtml);
}
else
builder.HtmlBody = BodyHtml;
builder.TextBody = BodyText ;
if (Format == false)
{
builder.Attachments.Add(addImage(filesDirectory + EmailLogoHeader));
builder.Attachments.Add(addImage(filesDirectory + EmailLogoFooter));
}
email.Body = Format == false ? new TextPart(TextFormat.Text) { Text = builder.TextBody } : new TextPart(TextFormat.Html){ Text= builder.HtmlBody };
// send email
var smtp = new MailKit.Net.Smtp.SmtpClient();
smtp.Connect(SMTP, Int32.Parse(SMTPPORT), SecureSocketOptions.StartTls);
smtp.Authenticate(SMTPLOGIN, SMTPPWD);
smtp.Send(email);
smtp.Disconnect(true);
}
catch (Exception ex) { Log.Error(ex.Message + " : " + ex.InnerException + " - ENVOI_Constructor: ExecuteSendMailEx Method"); }
}
obviously, my first lines of the code are:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Web;
using TP;
using System.Net;
using System.Net.Mail;
using MimeKit;
using MimeKit.Text;
using MailKit.Net.Smtp;
using MailKit.Security;
using Serilog;
using System.Drawing;
using System.IO;
using MimeKit.Utils;
expected behavior: I tried everything to embed images to Emails sent with MailKit, but they always come out as
all variables contain correct values like SMTP hosting the Exchange server address or SMTPPORT containing the port, every variable is named like its meaning,
the EmailHeaderLogo & EmailFooterLogo contain the pathes like Mail\image.jpg,
I navigated to the parent folder because the files are on the parent folder and inside the path that exist on the variable,
sorry that the code may seem French, I'm not french but where I'm working is a french international company,
if you want any additional information, don't hesitate to ask me,
and thank you
The problem is that you are setting the message body incorrectly.
Replace the following line:
email.Body = Format == false ? new TextPart(TextFormat.Text) { Text = builder.TextBody } : new TextPart(TextFormat.Html){ Text= builder.HtmlBody };
with this:
email.Body = builder.ToMessageBody();
I don't understand Format is supposed to do, but it looks like if Format is false, then you want only plain-text?
If so, you'll want to change your code to the following:
public void ExecuteSendMailEx(AccesBase accesBase, string From, string Subjet, bool Format, string EmailLogoHeader, string EmailLogoFooter, string ReplyTo, string ReturnPath, string BodyHtml, string BodyText, string Destinataire, string IdLangage, string CopieCachee, string PJ, string SMTP, string SMTPPORT, string SMTPLOGIN, string SMTPPWD, ref int RTN)
{
try
{
Log.Information("ENVOI_Constructor ExecuteSendMailEx has begun");
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(From));
email.To.Add(MailboxAddress.Parse(Destinataire));
email.ReplyTo.Add(MailboxAddress.Parse(ReplyTo));
if (!string.IsNullOrEmpty(CopieCachee))
email.Bcc.Add(MailboxAddress.Parse(CopieCachee));
email.Subject = Subjet;
email.Sender = (MailboxAddress.Parse(SMTPLOGIN));
var currentDirectory = Directory.GetCurrentDirectory();
var parentDirectory = Directory.GetParent(currentDirectory).FullName;
var filesDirectory = Path.Combine(parentDirectory, "Files");
var builder = new BodyBuilder();
if (Format)
{
// If we have any headers or footers, inject those into the HTML body
if (!string.IsNullOrEmpty(EmailLogoHeader) && !string.IsNullOrEmpty(EmailLogoFooter))
{
var imageHead = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoHeader));
imageHead.ContentId = MimeUtils.GenerateMessageId();
var imageFoot = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoFooter));
imageFoot.ContentId = MimeUtils.GenerateMessageId();
builder.HtmlBody = string.Format(#"<img src='cid:{0}'><br>{1}<br><img src='cid:{2} '>", imageHead.ContentId, BodyHtml, imageFoot.ContentId);
}
else if (!string.IsNullOrEmpty(EmailLogoFooter))
{
var imageFoot = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoFooter));
imageFoot.ContentId = MimeUtils.GenerateMessageId();
builder.HtmlBody = string.Format(#"{0}<br><img src='cid={1}'>", BodyHtml, imageFoot.ContentId);
}
else if (!string.IsNullOrEmpty(EmailLogoHeader))
{
var imageHead = builder.LinkedResources.Add(Path.Combine(filesDirectory, EmailLogoHeader));
imageHead.ContentId = MimeUtils.GenerateMessageId();
builder.HtmlBody = string.Format(#"<img src='cid:{0}'><br>{1}", imageHead.ContentId, BodyHtml);
}
else
{
builder.HtmlBody = BodyHtml;
}
}
else
{
// No HTML body is desired, so just add the header and footer images as attachments instead.
if (!string.IsNullOrEmpty(EmailLogoHeader))
builder.Attachments.Add(Path.Combine(filesDirectory, EmailLogoHeader));
if (!string.IsNullOrEmpty(EmailLogoFooter))
builder.Attachments.Add(Path.Combine(filesDirectory, EmailLogoFooter));
}
builder.TextBody = BodyText;
email.Body = builder.ToMessageBody();
// send email
using (var smtp = new MailKit.Net.Smtp.SmtpClient())
{
smtp.Connect(SMTP, Int32.Parse(SMTPPORT), SecureSocketOptions.StartTls);
smtp.Authenticate(SMTPLOGIN, SMTPPWD);
smtp.Send(email);
smtp.Disconnect(true);
}
}
catch (Exception ex)
{
Log.Error(ex.Message + " : " + ex.InnerException + " - ENVOI_Constructor: ExecuteSendMailEx Method");
}
}
Note: I took the liberty of changing your code to use string.IsNullOrEmpty() instead of doing a direct comparison with "" as well as fixing your code to use Path.Combine(). You should really get into the habit of using Path.Combine(), especially, since it will help make your code portable to non-Windows platforms if you ever want to run your code on .NET Core (where it may run on a Linux or Mac).
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.
I'm trying to send an email with an attachment from a form to myself. This works succesfully when I add a .pdf file as an attachment. But it fails when I try a .doc or .docx file.
I've added some validation in javascript, but that accepts every file type I need:
var validFileTypes = ["doc", "docx", "pdf", "tiff"];
This is my c# code to check my form and send the email:
private bool SendJobMail()
{
var client = new MailerServiceReference.IemailClient();
var succeeded = false;
string _recipient = "jobs#company.eu";
string _firstName = firstName.Value;
string _lastName = lastName.Value;
string _telNr = phone.Value;
string _motivation = motivation.Value;
string _sender = "info#company.eu";
int vacId = Int32.Parse(vacancyId.Value);
string vacTitle = _vacancies.Find(vac => vac.Id == vacId).Title;
string subject = string.Format("Application from {0} {1} for {2}", _firstName, _lastName, vacTitle);
_motivation += string.Format("\n\n{0}{1}\n{2}\n{3}", _firstName, _lastName, email.Value, _telNr);
//set up and add an attachment
string attachmentFilename = Path.GetFileName(cv.PostedFile.FileName);
Attachment attachment = new Attachment(cv.FileContent, attachmentFilename, MediaTypeNames.Application.Octet); //can interpret PDF and richtextdocument
ContentDisposition disposition = attachment.ContentDisposition; //disposition necessary for some mailing applications
disposition.CreationDate = File.GetCreationTime(attachmentFilename);
disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
disposition.FileName = Path.GetFileName(attachmentFilename);
disposition.Size = cv.PostedFile.ContentLength;
disposition.DispositionType = DispositionTypeNames.Attachment;
try
{
client.Open();
client.SendEmail("CompanyPublicSite", _sender, _recipient, subject, _motivation);
succeeded = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
client.Close();
}
return succeeded;
}
If you need any additional code, let me know.
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);