Mail doesn't work with multiple to addresses [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Unable to send an email to multiple addresses/recipients using C#
I have used below code to send mail in script task
string MailFromName = "Admin";
System.Net.Mail.SmtpClient mailobj = new System.Net.Mail.SmtpClient();
System.Net.Mail.MailAddress MailFrom = new System.Net.Mail.MailAddress(MailFromEmail, MailFromName);
System.Net.Mail.MailAddress MailTo = new System.Net.Mail.MailAddress(MailToEmail, MailToEmail);
System.Net.Mail.MailMessage mailmsg = new System.Net.Mail.MailMessage(MailFrom, MailTo);
mailmsg.IsBodyHtml = true;
mailmsg.Subject = strMessageSubject;
mailmsg.Body = strMessageBody;
mailobj.Host = strSMTPServerName;
mailobj.Send(mailmsg);
It is working fine when I am using MailToEmail as "myaddress#myMail.com" i.e. for one email address
but this doesn't send any mail(also it dosen't fail) when I have multiple adress in to list
ex: "MyAdress#MyMail.com; MySecondAddress#MyMail.com"
How to resolve this?
EDIT New Code
string MailFromName = "Admin";
System.Net.Mail.SmtpClient mailobj = new System.Net.Mail.SmtpClient();
System.Net.Mail.MailAddress MailFrom = new System.Net.Mail.MailAddress(MailFromEmail, MailFromName);
System.Net.Mail.MailAddress MailTo = new System.Net.Mail.MailAddress(MailToEmail, MailToEmail);
System.Net.Mail.MailMessage mailmsg = new System.Net.Mail.MailMessage(MailFrom, MailTo);
mailmsg.IsBodyHtml = true;
mailmsg.Subject = strMessageSubject;
mailmsg.Body = strMessageBody;
foreach (string str in multipleToMsg)
{
mailmsg.To.Add(str);
}
mailobj.Host = strSMTPServerName;
mailobj.Send(mailmsg);

You've not shown how exactly you are adding the recipients. However to add multiple recipients you add to the "To" collection:
MailMessage message = new MailMessage();
message.To.Add("sillyjoe#stackoverflow.com");
"To" is a collection of MailAddresses. Make sure you are adding it to that collection and not attempting to concatenate email addresses all into one MailAddress object.

Accoring to MSDN: MailMessage Class the "To" property is a collection of MailAddresses
so you just need to do something like
mailmsg.To.Add(new System.Net.Mail.MailAddress(MailToEmail, MailToEmail));
mailmsg.To.Add(new System.Net.Mail.MailAddress(MailToEmail2, MailToEmail2))
or in a foreach loop
//get email addresses into a collection called emailAdds
foreach (var emailAdd in emailAdds)
{
mailmsg.To.Add(new System.Net.Mail.MailAddress(emailAdd, emailAdd ));
}

To specify multiple addresses you need to use the To property which is a MailAddressCollection
message.To.Add("one#example.com, one#example.com"));
message.To.Add("two#example.com, two#example.com"));

Related

Get a list of files in a folder and list them in an e-mail body

I'm new to C# and am trying to get a list of files from a directory and then send them in an e-mail. I can do both things individually, but just can't seem to work out. Here is my basic code to get a list of files:
foreach (string str in Directory.GetFiles(path))
{
Message.Print(str);
}
For my e-mail code, I have this:
SmtpClient smtpClient = new SmtpClient(server, Port);
smtpClient.Credentials = new System.Net.NetworkCredential(username, password);
smtpClient.EnableSsl = ssl;
MailAddress fromAddress = new MailAddress(sender);
MailMessage message = new MailMessage();
message.From = fromAddress;
message.Subject = "Test e-mail";
message.IsBodyHtml = false;
message.Body = "List directory content here";
message.To.Add(reciever);
smtpClient.Send(message);
No matter what I try, I just can't seem to work out how to list the directory contents in the e-mail body. Can anyone assist?
Directory.GetFiles(path) is an array, you can use string.Join to get an string out of that instead of your current foreach loop, then you just use the resulting string for message.Body.
message.Body = sting.Join(",", Directory.GetFiles(path))
This is the initial step to get it working, validations need to be done in order to make this production ready. Check Directory.GetFiles exceptions to get an idea of all the stuff that can go wrong with this code.

How to send group emails asp.net/C# depending on select query

I am trying to send a group email depending on emails gathered from a select query called emailresults.
This is the code I have got so far but I am receiving error:
Could not send the e-mail - error: The specified string is not in the form required for an e-mail address
MailMessage message = new MailMessage("queensqsis#gmail.com", "queensqsis#gmail.com");// to & from
message.To.Add(emailresult);
message.Subject = "Test";
message.Body = "test ";
SmtpClient Client = new SmtpClient();
Client.Send(message);
If emailResults is some kind of Enumerable you will need to add each email address string from the Enumerable to the MailMessage.To MailAddressCollection. It's hard to say exactly how to do this without knowing the Type of emailresults. I expect you need something along these lines.
MailMessage message = new MailMessage("queensqsis#gmail.com", "queensqsis#gmail.com");// to & from
for(var item in emailresult){
message.To.Add(item);
}
message.Subject = "Test";
message.Body = "test ";
SmtpClient Client = new SmtpClient();
Client.Send(message);
If you can confirm what Type emailResults is it will be much easier to provide a clear solution.
In your comment above you state that emailresult is a select query result, so some sort of enumarable? Or as another poster suggested a long string separated by commas or semicolons?
Try doing one of these suggestions...
MailMessage message = new MailMessage("queensqsis#gmail.com", "queensqsis#gmail.com");// to & from
//For each item in the list, add it to the list of "To" recipients
emailresult.ForEach(r => message.To.Add(r)) ;
//OR IF THE ADDRESS IS A PROPERTY OF THE ITEM
emailresult.ForEach(r => message.To.Add(r.MyEmailAddressProperty)) ;
//OR IF emailresult is some sort of string list, "email1,email2,email3" or similar then
foreach (string oneEmail in emailresult.Split(","))
{
message.To.Add(oneEmail);
}
message.Subject = "Test";
message.Body = "test ";
SmtpClient Client = new SmtpClient();
Client.Send(message);

Send Email using SMTP in C# + Template Processing Mail Merge

Currently i am using SMTP Client to send email in C#.
I have one email template defined in which i replace the value at run time.
MailDefinition mailDefinition = new MailDefinition();
mailDefinition.BodyFileName = "~/Email-Templates/File.html";
mailDefinition.From = "abc#gmail.com";
//Create a key-value collection of all the tokens you want to replace in your template...
ListDictionary replacements = new ListDictionary();
replacements.Add("<%FirstName%>", "abc");
replacements.Add("<%LastName%>", "xyz");
replacements.Add("<%ManagerName%>", "Tom");
replacements.Add("<%Address1%>", "USA");
replacements.Add("<%Address2%>", "USA");
replacements.Add("<%City%>", "uk");
replacements.Add("<%State%>", "uk");
replacements.Add("<%Zip%>", "9876543");
string mailTo = string.Format("{0} {1} <{2}>", "abc", "xyz", "abc#gmail.com");
MailMessage mailMessage = mailDefinition.CreateMailMessage(mailTo, replacements, this);
mailMessage.From = new MailAddress("abc#gmail.com", "test site");
mailMessage.IsBodyHtml = true;
mailMessage.Subject = "User Details";
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("abc#gmail.com", "aaaaaaaa"),
EnableSsl = true
};
client.Send(mailMessage);
Template looks like this :
Hello <%FirstName%> <%LastName%>,
Thank you for creating an account with us.
Here are your details:
Your Manager is <%ManagerName%>
<%Address1%>,
<%Address2%>
<%City%>, <%State%> <%Zip%>
Thank You,
abc
Now my question is in future i want to add newfield to the email template , i need to add the same to my code and rebuild the system, this is what i dont want , i dont want to build my system everytime.
Is there a way or some other approach where i need not to build the system everytime ?
I can configure this from some where else ?
Thanks.

HTML based email not working properly in asp.net web form

I am working on web form which collects certain user information from users and sends confirmation by email. I am trying to user the following approach to send the HTML email as it make managing HTML based email easy.
https://gist.github.com/1668751
I made necessary changes to the code but it is not working. I read other related article to make it work but i am doing something wrong.
Following line of code generates error The replacements dictionary must contain only strings.
MailMessage msgHtml = mailDef.CreateMailMessage(to, replacements, MessageBody, new System.Web.UI.Control());
I have made many change to the code but it doesnt seem to work for me. I would appreciate help to make this code work.
If i comment the above line of code with some other changes then i can send email but i can't replace the token. Any easy approach to replace token is also welcome.
Below is the Complete code i am using right now
String to, subject, Name;
subject = "Booking Confirmation";
Name = txtName.text;
ListDictionary replacements = new ListDictionary();
replacements.Add("<%Name%>", Name);
replacements.Add("<%Email%>", objVR.Email);
replacements.Add("<%CompanyName%>", objVR.CompanyName);
replacements.Add("<%BookingDate%>", objVR.BookingDate);
replacements.Add("<%BookingTime%>", objVR.TimeSlot);
replacements.Add("<%NoOfVisitors%>", objVR.NoOfVisitors);
replacements.Add("<%BookingCode%>", objVR.BookingUniqueID);
MailDefinition mailDef = new MailDefinition();
string MessageBody = String.Empty;
string filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
using (StreamReader sr = new StreamReader(filePath + #"\en\VREmailEnglish.htm"))
{
MessageBody = sr.ReadToEnd();
}
MailMessage msgHtml = mailDef.CreateMailMessage(to, replacements, MessageBody, new System.Web.UI.Control());
string message = msgHtml.Body.ToString();
Helper.SendTokenEmail(to, subject, msgHtml, isHtml);
public static void SendTokenEmail(string to, string subject, string mailMessage, bool isHtml)
{
try
{
// Create a new message
var mail = new MailMessage();
// Set the to and from addresses.
mail.From = new MailAddress("noreply#somedomain.net");
mail.To.Add(new MailAddress(to));
// Define the message
mail.Subject = subject;
mail.IsBodyHtml = isHtml;
mail.Body = mailMessage.ToString();
//Object userState = mailMessage;
// Create a new Smpt Client using Google's servers
var mailclient = new SmtpClient();
mailclient.Host = "mail.XYZ.net";
//mailclient.Port = 587; //ForGmail
mailclient.Port = 2525;
mailclient.EnableSsl = false;
mailclient.UseDefaultCredentials = true;
// Specify your authentication details
mailclient.Credentials = new System.Net.NetworkCredential("noreply#somedomain.net", "XYZPassword");
mailclient.Send(mail);
mailclient.Dispose();
}
catch (Exception ex)
{
}
}
As pointed out by HatSoft the ListDictionary accepts objects as key and value so this looks like it should work.
But reading the docs for the CreateMailMessage() method here http://msdn.microsoft.com/en-us/library/0002kwb2.aspx indicates you need to convert the value to a string otherwise it will throw an ArgumentException.
So to fix make sure all values you add to the ListDictionary are converted to string i.e
objVR.BookingDate.ToString()

ASP.NET emailing to multiple emails

I have this code here...
MailAddress from = new MailAddress("noreply#fakeemail.com", "IPC Orders");
MailAddress to = new MailAddress("email1#fakeemail.com.com");
MailMessage mail = new MailMessage(from, to);
mail.To.Add("email2#fakeemail.com");
mail.To.Add("email3#fakeemail.com");
Obviously this is not the full code, but when I try to send an email to multiple email address is doesnt send, if I comment out these two lines...
mail.To.Add("email2#fakeemail.com");
mail.To.Add("email3#fakeemail.com");
It works and will send it to the first email MailAddress to = new MailAddress("email1#fakeemail.com.com");
Whats wrong with my code
USE AddressCollection FOR ADDING MULTIPLE TO ADDRESSES
LIKE
mail.To = new AddressCollection( "email2#fakeemail.com, email3#fakeemail.com");
you can try to add add all your email addresses to a list, then just iterate over that list and send a mail at each element
List<string> emailAddress = new List<string>();
emailAddress.add("email1#em.com");
emailAddress.add("email2#em.com"); // ... etc
foreach (string email in emailAddress)
{
MailMessage mail = new MailMessage(from, email);
//+ more stuff
}

Categories