Sending mail to multiple recipients via Interop library C# - c#

I'm developing a desktop application that has mail sending option. I have the following code to that and it works perfect for only 1 recipient:
DialogResult status;
status = MessageBox.Show("Some message", "Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (status == DialogResult.OK)
{
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 = "<html>" +
"<body>" +
"some html text" +
"</body>" +
"</html>";
int iPosition = (int)oMsg.Body.Length + 1;
//Subject line
oMsg.Subject = txt_mailKonu.Text;
oMsg.Importance = Outlook.OlImportance.olImportanceHigh;
// Recipient
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
//Following line causes the problem
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(senderForm.getRecipientList().ToString());
oRecip.Resolve();
//oRecip.Resolve();
// Send.
oMsg.Send();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
MessageBox.Show("Successful", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
MessageBox.Show("Failed", "Eror", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I get the error at the bold line where I'm adding multiple recipients in the following pattern:
john.harper#abcd.com; adam.smith#abcd.com
It works fine for 1 address but when I get multiple addresses separated it throws COM Exception - Outlook cannot resolve one or more names.
Hope you'll help me with this.

Did you try to add multiple recipients to oMsg.Recipients?
// I assume that senderForm.getRecipientList() returns List<String>
foreach(String recipient in senderForm.getRecipientList())
{
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(recipient);
oRecip.Resolve();
}
If needed, you could explode senderForm.getRecipientList().ToString() with
String [] rcpts = senderForm.getRecipientList().ToString().Split(new string[] { "; " }, StringSplitOptions.None);
and use new object in foreach loop.

Related

Write duplicate rows found in the list to email body

The question is how to write values from list to email body if I am getting the whole row as an output? Any suggestions how this should be done?
No errors, but also no output.
// Check if duplicates has been found = list is not empty. Write duplicates to Email message by creating a string with duplictes.
if (duplicatesPOSTADR?.Any() != false)
{
string combindedString = string.Join("\n", duplicatesPOSTADR);
string EmailBody = "There was an error and" +
"following duplicates has been found in POSTADR column: " + combindedString; // collect duplicate values to "combindedString"
CreateMailItem(EmailBody); // Create email message with body text
Console.WriteLine(EmailBody); // write to console
}
}
Output in outlook email should look like:
There was an error and following duplicates has been found in POSTADR column:
Fiat, Punto, 500, P4
BMW, E64, SE0, P4
Here is separate method I use for email:
public static void CreateMailItem(string EmailBody)
{
//Outlook.MailItem mailItem = (Outlook.MailItem)
// this.Application.CreateItem(Outlook.OlItemType.olMailItem);
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
//string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"Data\Robot.jpg");
//string[] files = File.ReadAllLines(path);
mailItem.Subject = "There was an error";
mailItem.To = "email#example.com";
//mailItem.Attachments.Add(files);
mailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
string msgHTMLBody = "<html><body>" +
EmailBody + "</body></html>";
mailItem.HTMLBody = msgHTMLBody;
mailItem.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh;
mailItem.Display(false);
mailItem.Send();
Environment.Exit(-1);
}
Here is full process that can be tested: https://dotnetfiddle.net/qEnpmj
It seems you want to show POSTADR value which is duplicate over multiple rows. You should Select(x => x.POSTADR) and apply Distinct() on that like below.
string combindedString = string.Join("\n", duplicatesPOSTADR.Select(x => x.POSTADR).Distinct());

send mail with attachement in c# using outlook

I m getting error when i m trying to send email to different Recipients with their respective attachment. i m using looping to change the Recipients and attachment but getting error. pls help to resolve this issue
my code is
private void BtnEmail_Click(object sender, EventArgs e)
{
try
{
string[] fileEntries = System.IO.Directory.GetFiles(txtPdfFiles.Text, "*.pdf");
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
if (RtxtBox.Text == "")
{
MessageBox.Show("Please set Mail body text");
GrpMailBody.Visible = true;
}
else
{
oMsg.HTMLBody = RtxtBox.Text;
}
if (RtxtSubject.Text == "")
{
MessageBox.Show("Please Enter Mail Subject");
GrpMailBody.Visible = true;
}
else
{
oMsg.Subject = RtxtSubject.Text;
}
String sDisplayName = "MyAttachment";
int iPosition = (int)oMsg.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
for (int i = 0; i <= grvExcelData.RowCount; i++)
{
string EmaildID = grvExcelData.Rows[i].Cells[3].Value.ToString();
string sFileName = grvExcelData.Rows[i].Cells[5].Value.ToString()+".pdf";
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(EmaildID);
foreach (string fileName in fileEntries)
{
string fileN = "";
string xfileName;
xfileName=System.IO.Path.GetFileName(fileName);
if (xfileName == sFileName)
{
Outlook.Attachment oAttach = oMsg.Attachments.Add(#fileName, iAttachType, iPosition, sDisplayName); //getting error in this line
}
else
{
}
}
oRecip.Resolve();
oMsg.Send();
oRecip = null;
//oRecips = null;
oMsg = null;
oApp = null;
}
Add this--
Add reference Microsoft.Office.Interop.Outlook
using Outlook = Microsoft.Office.Interop.Outlook;
public void sendEMailThroughOUTLOOK()
{
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!!";
//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(#"C:\\fileName.jpg", 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("EmailAddress");
oRecip.Resolve();
// Send.
oMsg.Send();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}//end of try block
catch (Exception ex)
{
}//end of catch
}//end of Email Method
Try to add Outlook Inspector as described here:
https://groups.google.com/forum/#!msg/microsoft.public.outlook.program_vba/lLJwbwwl-XU/gRuQYRpJtxEJ
using Outlook = Microsoft.Office.Interop.Outlook;
try
{
string[] fileEntries = System.IO.Directory.GetFiles(txtPdfFiles.Text, "*.pdf");
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Inspector oInspector = oMsg.GetInspector;
// ...
}

Getting exact File Path with File Upload to send file via Email C# ASP.NET

I want to send a file via email using c# ASP.net (Maybe more files too, but for the moment I'm concerned about sending at least only one file)
For the moment, I do have a method that does work if you want to send an Email
public string EnviarMensaje(int intIdVendedor, string strCorreoPara, string strCorreosAdicionales, string strTema, string strMensaje, string strRuta)
{
string strResultado="";
DataTable dt = ConexionBD.GetInstanciaConexionBD().GetVendedorEspecifico(intIdVendedor);
string strCuerpo = strMensaje + "\n\n\n\nMensaje Enviado Por:\n" + dt.Rows[0]["Vendedor"] + "\n" + dt.Rows[0]["Email"] + "\n" + dt.Rows[0]["Telefono"];
string[] strListaCorreos = strCorreosAdicionales.Split(new Char[] {' ', ','}, StringSplitOptions.RemoveEmptyEntries);
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpout.secureserver.net");
mail.Subject = strTema;
mail.Body = strCuerpo;
mail.From = new MailAddress(strCorreoDe);
mail.To.Add(strCorreoPara);
foreach (string c in strListaCorreos)
{
mail.To.Add(c);
}
if (strRuta != "")
{
Attachment attachment;
attachment = new Attachment(strRuta);
mail.Attachments.Add(attachment);
}
SmtpServer.Port = 80;
SmtpServer.Credentials = new System.Net.NetworkCredential(strCorreoDe, strContrasena);
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
strResultado = "Exito";
}
catch (Exception ex)
{
strResultado = ex.ToString();
}
return strResultado;
}
in aspx I have
<asp:FileUpload ID="fileUploadArchivos" runat="server" />
<asp:ImageButton ID="imgBtnEnviar" runat="server" Height="60px" Width="60px" ImageUrl="~/img/iconos/email.png" CausesValidation = "True" ValidationGroup="vgpCorreo" onclick="imgBtnEnviar_Click" />
and on the cs I have
EnviarEmail objEmail = new EnviarEmail();
protected void imgBtnEnviar_Click(object sender, ImageClickEventArgs e)
{
if (fileUploadArchivos.HasFile)
{
strArchivo = Path.GetTempFileName();\\RIGHT NOW I LEFT IT THIS WAY, BUT I NOW THAT HERE IS THE PROBLEM, I DON'T KNOW WHTAT CAN I DO HERE
}
string strResultado = objEmail.EnviarMensaje((int)Session["IdVendedor"], lblCorreoPara.Text, tbxCorreoPara.Text, tbxTema.Text, tbxMensaje.Text, strArchivo);
}
However, the problem is in a FileUpload.
I have tried many methods like, Server.MapPath, Path.GetFileName, GetDirectoryName, GetFullPath, GetPathRoot... and I'm always getting either nothing, only the filename or a completely different path (I guess is a server kind of path)..
I only for the moment want to get a file path as simple as C:\Test.txt for example...
I suppose that if I can get that exact string from the FileUpload, I'll be able to send it... However, I can't figure out how to make it work.
Hope you can help me
Thanks
If you need a local copy of the file uploaded kept on the server you can just do
fuFileUpload.SaveAs(MapPath(filepath));
Then your strRuta can use the file you just saved via
strRuta = Server.MapPath(filepath);
ready to pass into the new Attachment object.
You don't need to save the file at all to disk, not if all you want to do with it is add it as an attachment.
FileUpload has a FileContent property that is a Stream - some of the constructors of the Attachment class take a stream as a parameter.
The solution is to pass this stream to your method and use it directly.
In code behind:
string strResultado = objEmail.EnviarMensaje((int)Session["IdVendedor"],
lblCorreoPara.Text,
tbxCorreoPara.Text,
tbxTema.Text,
tbxMensaje.Text,
fileUploadArchivos.FileContent);
In your class:
public string EnviarMensaje(int intIdVendedor,
string strCorreoPara,
string strCorreosAdicionales,
string strTema,
string strMensaje,
Stream attachmentData)
{
...
var attachment = new Attachment(attachmentData, "nameOfAttachment");
...
}
You can try with this, using a stream instead of a simple text:
public string EnviarMensaje(int intIdVendedor, string strCorreoPara, string strCorreosAdicionales, string strTema, string strMensaje, string strRuta)
{
string strResultado="";
DataTable dt = ConexionBD.GetInstanciaConexionBD().GetVendedorEspecifico(intIdVendedor);
string strCuerpo = strMensaje + "\n\n\n\nMensaje Enviado Por:\n" + dt.Rows[0]["Vendedor"] + "\n" + dt.Rows[0]["Email"] + "\n" + dt.Rows[0]["Telefono"];
string[] strListaCorreos = strCorreosAdicionales.Split(new Char[] {' ', ','}, StringSplitOptions.RemoveEmptyEntries);
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpout.secureserver.net");
mail.Subject = strTema;
mail.Body = strCuerpo;
mail.From = new MailAddress(strCorreoDe);
mail.To.Add(strCorreoPara);
foreach (string c in strListaCorreos)
{
mail.To.Add(c);
}
bool hasAttachment = !string.IsNullOrWhitespace(strRuta);
System.IO.FileStream stream = null;
Attachment attachment = null;
if (hasAttachment)
{
// Create a file stream.
stream = new FileStream(strRuta, FileMode.Open, FileAccess.Read);
// Define content type.
ContentType contentType = new ContentType();
contentType.MediaType = MediaTypeNames.Text.Plain; // or whatever your attachment is
// Create the attachment and add it.
attachment = new Attachment(stream, contentType);
mail.Attachments.Add(attachment);
}
SmtpServer.Port = 80;
SmtpServer.Credentials = new System.Net.NetworkCredential(strCorreoDe, strContrasena);
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
strResultado = "Exito";
// Don't forget to release the resources if the attachment has been added
if (hasAttachment)
{
data.Dispose();
stream.Close();
stream.Dispose();
}
}
catch (Exception ex)
{
strResultado = ex.ToString();
}
return strResultado;
}

Microsoft Outlook adding cc to email

I currently have existing code that automates and email and sends files. I now need to add a cc. I have looked all over, but can't seem to find out with my existing code. Any help would be greatly appreciated. Thank you.
private void button13_Click(object sender, EventArgs e)
{
//Send Routing and Drawing to Dan
// 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);
//Add a recipient
Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add("email#email.com");
oRecip.Resolve();
//Set the basic properties.
oMsg.Subject = "Job # " + textBox9.Text + " Release (" + textBox1.Text + ")";
oMsg.HTMLBody = "<html><body>";
oMsg.HTMLBody += "Job # " + textBox9.Text + " is ready for release attached is the Print and Routing (" + textBox1.Text + ")";
oMsg.HTMLBody += "<p><a href='C:\\Users\\RussellS\\Desktop\\Russell Eng Reference\\" + textBox1.Text + ".PDF'>" + textBox1.Text + " Drawing";
oMsg.HTMLBody += "<p><a href='C:\\Users\\RussellS\\Desktop\\" + textBox1.Text + ".PDF'>" + textBox1.Text + " Routing" + "</a></p></body></html>";
//Send the message
oMsg.Send();
//Explicitly release objects.
oRecip = null;
oMsg = null;
oApp = null;
MessageBox.Show(textBox1.Text + " Print and Routing Sent");
}
According to MSDN there's a CC property on the MailItem class.
string CC { get; set; }
Which can be used to set the names of the CC recipients.
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._mailitem.cc.aspx
To modify the recipients you can add them to the Recipients collection:
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.recipients.aspx
Which you would use like:
oMsg.Recipients.Add("foo#bar.com");
Please follow this code for adding CC and BCC:
private void SetRecipientTypeForMail()
{
Outlook.MailItem mail = Application.CreateItem(
Outlook.OlItemType.olMailItem) as Outlook.MailItem;
mail.Subject = "Sample Message";
Outlook.Recipient recipTo =
mail.Recipients.Add("someone#example.com");
recipTo.Type = (int)Outlook.OlMailRecipientType.olTo;
Outlook.Recipient recipCc =
mail.Recipients.Add("someonecc#example.com");
recipCc.Type = (int)Outlook.OlMailRecipientType.olCC;
Outlook.Recipient recipBcc =
mail.Recipients.Add("someonebcc#example.com");
recipBcc.Type = (int)Outlook.OlMailRecipientType.olBCC;
mail.Recipients.ResolveAll();
mail.Display(false);
}

Save content of Email body in outlook to a file

i want to save the contents of the Email Body in outlook to a file. I am able to save the entire message .msg but i want to save only the html content of the body.
for example:
In the outlook email body i have a table i want to save that table to a file.
the script which i am working on:
public void GetAttachments()
{
Microsoft.Office.Interop.Outlook.Application myolApp = default(Microsoft.Office.Interop.Outlook.Application);
Microsoft.Office.Interop.Outlook.NameSpace ns = default(NameSpace);
MAPIFolder Inbox = default(MAPIFolder);
object Item = null;
Attachment Atmt = default(Attachment);
string FileName = null;
string subject = null;
string AttachmentName = null;
string Body = null;
string SenderName = null;
string SenderEmailAddress = null;
string CreationTime = null;
int i = 0;
int j = 0;
try
{
myolApp = (Microsoft.Office.Interop.Outlook.Application)Interaction.CreateObject("Outlook.Application","");
ns = myolApp.GetNamespace("MAPI");
ns.Logon("", "", false, true);
Inbox = ns.Folders["Mailbox - Name"].Folders["Inbox"];
i = 0;
j = 1;
//Scan for attachments
foreach (object Item_loopVariable in Inbox.Items)
{
Item = Item_loopVariable;
System.Windows.Forms.Application.DoEvents();
if ((Item as MailItem) != null ? ((MailItem)Item).UnRead : false)
{
Body = ((Microsoft.Office.Interop.Outlook.MailItem)Item).Body;
((Microsoft.Office.Interop.Outlook.MailItem)Item).HTMLBody = Body;
((Microsoft.Office.Interop.Outlook.MailItem)Item).SaveAs(#"\\path\"+"filename", Microsoft.Office.Interop.Outlook.OlSaveAsType.olHTML );
j = j + 1;
}
}
//Clear Memory
Atmt = null;
Item = null;
ns = null;
}
catch (System.Exception ex)
{
MessageBox.Show("An unexpected error has occurred."
+ "\r\n" + "Please note and report the following information."
+ "\r\n" + "Script Name: GetAttachments"
+ "\r\n" + "Error Description: " + ex.Message
+ "\r\n" + "Error StackTrace: " + ex.StackTrace
, "Error!");
Atmt = null;
Item = null;
ns = null;
}
}
I need changes in these piece of code:
Body = ((Microsoft.Office.Interop.Outlook.MailItem)Item).Body;
((Microsoft.Office.Interop.Outlook.MailItem)Item).HTMLBody = Body;
((Microsoft.Office.Interop.Outlook.MailItem)Item).SaveAs(#"\\path\"+"filename", Microsoft.Office.Interop.Outlook.OlSaveAsType.olHTML );
Outlook has some issues with saving the body of an email, as far as the filesystem security goes. A workaround is to use the file system objects to save the body - worked for me.

Categories