Sending multiple e-mails using outlook MailItem in loop - c#

Hello I am developing an outlook Add-on, as part of the work flow it should take the mailItem body and subject, and for each recipient it should change the body of message according to recipient e-mail.
The problem is that it just sends the first e-mail and after Send(); it does not send the e-mail to other recipients
Outlook.Application application = Globals.ThisAddIn.Application;
Outlook.Inspector inspector = application.ActiveInspector();
Outlook.MailItem myMailItem = (Outlook.MailItem)inspector.CurrentItem;
myMailItem.Save();
if (myMailItem != null)
{
myMailItem.Save();
PorceesData(myMailItem);
}
..
..
..
..
private void ProcessData(MailItem oMailItem)
{
Recipients recipients = oMailItem.Recipients;
string Body = oMailItem.Body;
string To = oMailItem.To;
string CC = oMailItem.CC;
string bcc = oMailItem.BCC;
foreach (Recipient r in recipients)
{
if (r.Resolve() == true)
{
string msg = "Hello open the attached file (msg.html);
string address = r.Address;
oMailItem.Body = msg;
oMailItem.To = address;
oMailItem.Subject = "my subject"
foreach (Attachment t in oMailItem.Attachments)
{
t.Delete();
}
oMailItem.Attachments.Add(#"mydirectory");
oMailItem.Send();
}

_MailItem.Send() closes the current inspector. This isn't in the _MailItem.Send documentation, but is the actual Outlook implementation. You should probably come up with another approach. I'd suggest creating a new MailItem instance for each message you wish to send.
You can create a new MailItem using...
Outlook.MailItem eMail = (Outlook.MailItem)
Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);
eMail.Subject = subject;
eMail.To = toEmail;
eMail.Body = body;
eMail.Importance = Outlook.OlImportance.olImportanceLow;
((Outlook._MailItem)eMail).Send();
After sending to all recipients you can manually close the current inspector using the following (Send() implicitly calls this method)
((Outlook._MailItem)myMailItem).Close(Outlook.OlInspectorClose.olDiscard)

Related

How to exclude or remove a specific e-mail address from a sendEmail function in c#

I'm trying to remove or exclude a couple specific e-mail addresses from the CC e-mail address list. How should I do this? Here is the function:
private void SendEmail(string emailTo, string subject, string body)
{
using (SmtpClient client = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["SmtpServerAddress"]))
{
MailMessage email = new MailMessage();
email.From = new MailAddress(GetUserEmail());
string emailCc = ConfigurationManager.AppSettings["EmailCc"];
foreach (var item in emailTo.Split(';'))
{
email.To.Add(new MailAddress(item.Trim()));
}
foreach (var item in emailCc.Split(';'))
{
email.CC.Add(new MailAddress(item.Trim()));
}
email.Subject = subject;
email.IsBodyHtml = true;
email.Body = body;
return;
}
}
You put the emails you don't want into an array:
var badEmails = new [] { "a#a.aa", "b#b.bb" }
Then you use LINQ to remove them from the split:
var ccList = emailCc.Split(';').Where(cc => !badEmails.Any(b => cc.IndexOf(b, System.StringComparison.InvariantCultureIgnoreCase) > -1));
Then you add those in ccList to your email
You can try with this if you know email:
foreach (var item in emailCc.Split(';'))
{
if (!new string[] { "bad#gmail.com", "uncle#sam.com", "stack#overflow.com"}.Contains(email))
{
email.CC.Add(new MailAddress(item.Trim()));
}
}
instead of if statement you can use regular expression if you want to exclude some email with specific pattern.

C# - Send email with inline attachment WITHOUT Outlook's paperclip icon?

I have a system that sends emails with inline pictures. The problem is how Outlook 2013 displays the attachments. Can I update my code in a way that tells outlook not to display the paperclip icon seen here?
The idea is that I only want to display this icon when full sized pictures are attached. Not inline attachments.
Here's the code that generates the email. Create a basic console app, specify your To / mailserver / picture path, and run.
static void Main(string[] args)
{
Console.WriteLine("Prepping email message....");
var subject = "Test Subject With Inline";
var message = "<p>This is a test message.</p><br/><br/><p>[CompanyLogo]</p>";
var to = new List<string>();
to.Add("My.Name#company.com");
Console.WriteLine("Sending email message....");
if (SendMessageToFrom(subject, message, to, new List<string>()))
{
Console.WriteLine("Email sent! Check your inbox.");
}
else
{
Console.WriteLine("Error sending email!");
}
}
public static bool SendMessageToFrom(String subject, String message, List<String> to, List<String> cc)
{
try
{
// Construct the email
var sendMessage = new MailMessage()
{
IsBodyHtml = true,
From = new MailAddress("noreply#company.com"),
Subject = subject,
Body = message
};
if (sendMessage.Body.Contains("[CompanyLogo]"))
{
sendMessage.AlternateViews.Add(EmbedLogo(sendMessage.Body));
}
// Add the list of recipients
foreach (var recipient in to)
{
sendMessage.To.Add(recipient);
}
foreach (var recipient in cc)
{
sendMessage.CC.Add(recipient);
}
//Specify the SMTP server
var smtpServerName = "mailserver.company.com";
var mailClient = new SmtpClient(smtpServerName);
mailClient.Send(sendMessage);
return true;
}
catch
{
throw;
}
}
private static AlternateView EmbedLogo(string html)
{
var inline = new LinkedResource("img\\company-logo.jpg");
inline.ContentId = Guid.NewGuid().ToString();
html = html.Replace("[CompanyLogo]", string.Format(#"<img src='cid:{0}'/>", inline.ContentId));
var result = AlternateView.CreateAlternateViewFromString(html, null, System.Net.Mime.MediaTypeNames.Text.Html);
result.LinkedResources.Add(inline);
return result;
}
Update: Here's the code that did the trick:
private static MailMessage EmbedLogo(MailMessage mail)
{
var inline = new Attachment("img\\company-logo.jpg");
inline.ContentId = Guid.NewGuid().ToString();
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
mail.Body = mail.Body.Replace("[CompanyLogo]", string.Format(#"<img src='cid:{0}'/>", inline.ContentId));
mail.Attachments.Add(inline);
return mail;
}
And I also updated the main method to this:
if (sendMessage.Body.Contains("[CompanyLogo]"))
{
sendMessage = EmbedLogo(sendMessage);
}
Make sure your attachments have the Content-ID MIME header and the message's HTML body refers to them using the cid attribute : <img src="cid:xyz"> (where xyz is the value of the Content-ID MIME header).

splitting words from a text box using in asp.net

I m new To ASP.net i want to send mail to multiple people by using one textbox and every email address is separated by ,. Now I want to send mail to multiple people. My code is
public static void SendEmail(string txtTo, string txtSubject, string txtBody, string txtFrom)
{
try
{
MailMessage mailMsg = new MailMessage();
SmtpClient smtp = new SmtpClient("mail.valuesoft.org", 26);
smtp.Credentials = new NetworkCredential("mail#----.org", "#123");
mailMsg.From = new MailAddress(txtFrom);
mailMsg.To.Add(txtTo);
mailMsg.Subject = txtSubject;
mailMsg.Body = txtBody;
mailMsg.IsBodyHtml = true;
smtp.Send(mailMsg);
}
catch { }
}
If you are asking for how to parse a comma seperated list:
string[] recipients = txtTo.Split(',');
foreach (string recipient in recipients)
{
mailMsg.To.Add(recipient );
}

Exchange EWS get BCC Recipients

I am using EWS to create a StreamingSubscription on an inbox. It is listening for the NewMail event. I am able to pull the From Address, Subject, Body, To Address, CC Address but not the BCC Address. Is there any way to see this list?
CODE:
static void OnEvent(object sender, NotificationEventArgs args)
{
String from = null;
String subject = null;
String body = null;
String to = null;
StreamingSubscription subscription = args.Subscription;
// Loop Through All Item-Related Events
foreach (NotificationEvent notification in args.Events)
{
ItemEvent item = (ItemEvent)notification;
PropertySet propertySet = new PropertySet(ItemSchema.UniqueBody);
propertySet.RequestedBodyType = BodyType.Text;
propertySet.BasePropertySet = BasePropertySet.FirstClassProperties;
// Parse Email
EmailMessage message = EmailMessage.Bind(service, item.ItemId, propertySet);
from = message.From.Address;
subject = message.Subject;
body = message.Body.Text;
if (message.ToRecipients.Count > 0)
{
to = message.ToRecipients[0].Address;
body += "\n TO FIELD";
}
else if (message.CcRecipients.Count > 0)
{
to = message.CcRecipients[0].Address;
body += "\n CC FIELD";
}
/************** Does not work! BccRecipients is always empty *****************/
else if (message.BccRecipients.Count > 0)
{
to = message.BccRecipients[0].Address;
body += "\n BCC FIELD";
}
/************* REST OF CODE ************************/
}
}
That would kind of defeat the point of a blind-carbon-copy. I dont believe it can be done.
Consider using the Journaling feature of Exchange. This uses something called "Envelope Journaling" which includes BCC information for messages within the Exchange environment.
For everything that comes from external sources (gmail) no BCC information is available.
This might help:
http://gsexdev.blogspot.com/2011/06/processing-bccs-in-exchange-transport.html

Unable to send an email to multiple addresses/recipients using C#

I am using the below code, and it only sends one email - I have to send the email to multiple addresses.
For getting more than one email I use:
string connectionString = ConfigurationManager.ConnectionStrings["email_data"].ConnectionString;
OleDbConnection con100 = new OleDbConnection(connectionString);
OleDbCommand cmd100 = new OleDbCommand("select top 3 emails from bulk_tbl", con100);
OleDbDataAdapter da100 = new OleDbDataAdapter(cmd100);
DataSet ds100 = new DataSet();
da100.Fill(ds100);
for (int i = 0; i < ds100.Tables[0].Rows.Count; i++)
//try
{
string all_emails = ds100.Tables[0].Rows[i][0].ToString();
{
string allmail = all_emails + ";";
Session.Add("ad_emails",allmail);
Response.Write(Session["ad_emails"]);
send_mail();
}
}
and for sending the email I use:
string sendto = Session["ad_emails"].ToString();
MailMessage message = new MailMessage("info#abc.com", sendto, "subject", "body");
SmtpClient emailClient = new SmtpClient("mail.smtp.com");
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("abc", "abc");
emailClient.UseDefaultCredentials = true;
emailClient.Credentials = SMTPUserInfo;
emailClient.Send(message);
The problem is that you are supplying a list of addresses separated by semi-colons to the MailMessage constructor when it only takes a string representing a single address:
A String that contains the address of the recipient of the e-mail message.
or possibly a list separated by commas (see below).
Source
To specify multiple addresses you need to use the To property which is a MailAddressCollection, though the examples on these pages don't show it very clearly:
message.To.Add("one#example.com, two#example.com"));
The e-mail addresses to add to the MailAddressCollection. Multiple e-mail addresses must be separated with a comma character (",").
MSDN page
so creating the MailMessage with a comma separated list should work.
This is what worked for me.
(recipients is an Array of Strings)
//Fuse all Receivers
var allRecipients = String.Join(",", recipients);
//Create new mail
var mail = new MailMessage(sender, allRecipients, subject, body);
//Create new SmtpClient
var smtpClient = new SmtpClient(hostname, port);
//Try Sending The mail
try
{
smtpClient.Send(mail);
}
catch (Exception ex)
{
Log.Error(String.Format("MailAppointment: Could Not Send Mail. Error = {0}",ex), this);
return false;
}
This function validates a comma- or semicolon-separated list of email addresses:
public static bool IsValidEmailString(string emailAddresses)
{
try
{
var addresses = emailAddresses.Split(',', ';')
.Where(a => !string.IsNullOrWhiteSpace(a))
.ToArray();
var reformattedAddresses = string.Join(",", addresses);
var dummyMessage = new System.Net.Mail.MailMessage();
dummyMessage.To.Add(reformattedAddresses);
return true;
}
catch
{
return false;
}
}
To send to multiple recipients I set up my recipient string with a comma as my separator.
string recipient = "foo#bar.com,foo2#bar.com,foo3#bar.com";
Then to add the recipients to the MailMessage object:
string[] emailTo = recipient.Split(',');
for (int i = 0; i < emailTo.GetLength(0); i++)
mailMessageObject.To.Add(emailTo[i]);
This code I use for send multiple mail for to, bcc and cc
MailMessage email = new MailMessage();
Attachment a = new Attachment(attach);
email.From = new MailAddress(from);//De
string[] Direcciones;
char[] deliminadores = { ';' };
//Seleccion de direcciones para el parametro to
Direcciones = to.Split(deliminadores);
foreach (string d in Direcciones)
email.To.Add(new MailAddress(d));//Para
//Seleccion de direcciones para el parametro CC
Direcciones = CC.Split(deliminadores);
foreach (string d in Direcciones)
email.CC.Add(new MailAddress(d));
//Seleccion de direcciones para el parametro Bcc
Direcciones = Bcc.Split(deliminadores);
foreach (string d in Direcciones)
enter code here`email.Bcc.Add(new MailAddress(d));
You are also allowed to pass MailMessage.To.Add()a comma separated list of valid RFC 822 e-mail addresses:
Nathaniel Borenstein <nsb#bellcore.com>, Ned Freed <ned#innosoft.com>
So the code would be:
message.To.Add("Nathaniel Borenstein <nsb#bellcore.com>, Ned Freed <ned#innosoft.com>");
Note: Any code released into public domain. No attribution required.

Categories

Resources