I want to send a message using Mandrill.I need the following code to do this:
Send the same message to all recipient without Each one of them see the address of the other recipient.
I used the following code :
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
string[] toResult = to.Split(new Char[] { ';' });
foreach (string s in toResult)
{
if (s != null && !s.Trim().Equals("") && !string.IsNullOrEmpty(s))
{
message.Bcc.Add(s);
}
}
if (!cc.Equals(""))
{
string[] ccResult = cc.Split(new Char[] { ';' });
foreach (string s in ccResult)
{
message.CC.Add(s);
}
}
if (!cci.Equals(""))
{
string[] cciResult = cci.Split(new Char[] { ';' });
foreach (string s in cciResult)
{
message.Bcc.Add(s);
}
}
message.Subject = subject;
message.From = new System.Net.Mail.MailAddress(from, from);
message.IsBodyHtml = true;
message.Body = "<html><body>" + body + "</body></html>";
message.BodyEncoding = System.Text.Encoding.UTF8;
System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString
(System.Text.RegularExpressions.Regex.Replace(body, #"<(.|\n)*?>", string.Empty), System.Text.Encoding.UTF8, "text/plain");
System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(body, System.Text.Encoding.UTF8, "text/html");
message.AlternateViews.Add(plainView);
message.AlternateViews.Add(htmlView);
message.Priority = System.Net.Mail.MailPriority.Normal;
smtp.Host = smtpH;
bool ssl = false;
if (useSSL.Equals("true"))
ssl = true;
if (ssl)
{
smtp.EnableSsl = true;
}
else
{
smtp.EnableSsl = false;
}
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(userName, password);
smtp.Port = Convert.ToInt32(port);
message.Headers.Add("Message-Id", String.Concat("<", DateTime.Now.ToString("yyMMdd"), ".",
DateTime.Now.ToString("HHmmss"), "#" + from.Split('#')[1].ToString() + ">"));
smtp.Send(message);
As you can see in the code snippet above, I added all the emails in the Bcc collection, but it does not work.
Does anyone have any idea about this problem.
If people are still seeing each other's email address, you'll probably want to go to the Sending Defaults page in your account and disable the option to expose recipients to one another. Otherwise, you can add a custom SMTP header to turn that option off, but it sounds like you probably don't want that on by default.
Related
How can I send an activation email when new users register in my website using asp.net c#? I have tried the steps described
this link but I have faced this error:
System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
Is there any solution to this or any other way to send an email?
this is my code
using (MailMessage mm = new MailMessage("sender#gmail.com", txtEmail.Text))
{
mm.Subject = "Account Activation";
string body = "Hello " + txtUsername.Text.Trim() + ",";
body += "<br /><br />Please click the following link to activate your account";
body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("CS.aspx", "CS_Activation.aspx?ActivationCode=" + activationCode) + "'>Click here to activate your account.</a>";
body += "<br /><br />Thanks";
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("sender#gmail.com", "<password>");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
The proposed duplicate did not solve the problem. I am already using port 587.
See the code below:
public static class email_utility
{
public static async Task<bool> send_email(this string body, string subject, string email, int try_count)
{
return await Task.Run(() =>
{
var cli = new SmtpClient();
using (var message = new MailMessage(config.sender_email, email))
{
message.Subject = subject;
message.SubjectEncoding = UTF8Encoding.UTF8;
message.Body = body;
message.BodyEncoding = UTF8Encoding.UTF8;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
for (var count = 0; count < try_count; ++count)
{
try
{
lock (config.sender_email)
{
cli.Send(message);
return true;
}
}
catch (SmtpFailedRecipientsException)
{
return false;
}
catch (SmtpException)
{
Thread.Sleep(config.send_timeout);
}
}
return false;
}
});
}
}
Try this, it works perfectly and you only have to change the fields that are before the var smtp = newSMTPCient.
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Trying to send email to multiple recipient using below code gives me this error:
The specified string is not in the form required for an e-mail
address.
string[] email = {"emailone#gmail.com","emailtow#gmail.com"};
using (MailMessage mm = new MailMessage("teset123321#gmail.com", email.ToString()))
{
try
{
mm.Subject = "sub;
mm.Body = "msg";
mm.Body += GetGridviewData(GridView1);
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtpout.server.net";
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential("email", "pass");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 80;
smtp.Send(mm);
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
}
catch (Exception ex)
{
Response.Write("Could not send the e-mail - error: " + ex.Message);
}
}
Change your using line to this:
using (MailMessage mm = new MailMessage())
Add the from address:
mm.From = new MailAddress("myaddress#gmail.com");
You can loop through your string array of e-mail addresses and add them one by one like this:
string[] email = { "emailone#gmail.com", "emailtwo#gmail.com", "emailthree#gmail.com" };
foreach (string address in email)
{
mm.To.Add(address);
}
Example:
string[] email = { "emailone#gmail.com", "emailtwo#gmail.com", "emailthree#gmail.com" };
using (MailMessage mm = new MailMessage())
{
try
{
mm.From = new MailAddress("myaddress#gmail.com");
foreach (string address in email)
{
mm.To.Add(address);
}
mm.Subject = "sub;
// Other Properties Here
}
catch (Exception ex)
{
Response.Write("Could not send the e-mail - error: " + ex.Message);
}
}
Presently your code:
new NetworkCredential("email", "pass");
treats "email" as an email address which eventually is not an email address rather a string array which contains the email address.
So you can try like this:
foreach (string add in email)
{
mm.To.Add(new MailAddress(add));
}
I was having this issue while working with SMTP.js but the issues were coming from the whitespace so please try and trim it off when working with emails. I hope this helps someone.
am am doing a website in mvc4 using c#. currently i test this in localhost. I want to send passwords to registering persons email. i use the following code.
//model
public void SendPasswordToMail(string newpwd,string email)
{
string mailcontent ="Your password is "+ newpwd;
string toemail = email.Trim();
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("paru.mr#gmail.com");
mail.To.Add(toemail);
mail.Subject = "Your New Password";
mail.Body = mailcontent;
//Attachment attachment = new Attachment(filename);
//mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password"); //is that NetworkCredential
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception e)
{
throw e;
}
}
//controller
string newpwd;
[HttpPost]
public ActionResult SendPassword(int Id,string email)
{
bool IsMember=CheckMember(Id);
if (IsMember == true)
{
newpwd = new Member().RandomPaswordGen();
}
.......//here i want to call that model
return View();
}
Is the model is right or not. and what should be the return type of this model(now it is void and i dont know how this call in controller). and how to get default NetworkCredential. Please help me
Network Credential is the user name and password of the email sender (as in case of company a defualt mail address like noreply#abccompany.com).
Hence use you gmail user name and password in that case.
And you could use following code to send email.
var client = new SmtpClient()
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
};
var from = new MailAddress(Email);
var to = new MailAddress(Email);
var message = new MailMessage(from, to) { Body = Message, IsBodyHtml = IsBodyHtml };
message.Body += Environment.NewLine + Footer;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = Subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
var nc = new NetworkCredential("me#gmail.com", "password");
client.Credentials = nc;
//send email
client.Send(message);
I am trying to send email to some of my colleagues using a program. This program is working fine at my own desktop but is giving an error
Bad sequence of commands. The server response was: You must authenticate first (#5.5.1)
on one of our servers in remote location. Can someone point out the error I have tried to change the position of the line of authentication. And I am not able to deduce much from the error. The same username and password are being used at both locations.
public static Boolean sendemail(String strFrom, string strTo, string strCC, string strBCC, string strReplyTO, string strSubject, string strBody, string strAttachmentPath, bool IsBodyHTML)
{
//Array arrToArray;
//char[] splitter = { ';' };
//arrToArray = strTo.Split(splitter);
MailMessage mm = new MailMessage();
bool flag = isEmailsString(strFrom);
if (flag)
{
mm.From = new MailAddress(strFrom);
}
flag = isEmailsString(strTo);
if (flag)
{
mm.To.Add(strTo);
}
flag = isEmailsString(strCC);
if (flag)
{
mm.CC.Add(strCC);
}
flag = isEmailsString(strBCC);
if (flag)
{
mm.Bcc.Add(strBCC);
}
flag = Regex.IsMatch(strReplyTO.Trim(), #"^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
if (strReplyTO != null)
{
if (flag)
{
mm.ReplyTo = new MailAddress(strReplyTO);
}
}
if (strSubject != null)
{
mm.Subject = strSubject;
}
mm.IsBodyHtml = IsBodyHTML;
if (!string.IsNullOrEmpty(strAttachmentPath))
{
Array attachmentArray;
char[] attachSplitter = { ',' };
attachmentArray = strAttachmentPath.Split(attachSplitter);
foreach (string s in attachmentArray)
{
string st = s.Trim();
if (!string.IsNullOrEmpty(st))
{
Attachment attach = new Attachment(st);
// Add the file attachment to this e-mail message.
mm.Attachments.Add(attach);
//strBodyFinal.Append(Environment.NewLine+"Go to the following link for more information"+Environment.NewLine);
//strBodyFinal.Append(st);
}
}
}
if (strBody != null)
{
mm.Body = strBody;
}
//foreach (string s in arrToArray)
// {
// mm.To.Add(new MailAddress(s));
// }
SmtpClient smtp = new SmtpClient();
try
{
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "my user name";
NetworkCred.Password = "my password";
smtp.Credentials = NetworkCred;
smtp.Host = "my company mail site";//host of your mail account
//smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Port = 2525;//port no of your mail account
smtp.Timeout = 500000;
smtp.Send(mm);
return true;
}
catch (Exception ex)
{
mm.Dispose();
smtp = null;
Console.WriteLine(ex.Message, ex.StackTrace);
return false;
}
}
I searched a lot about the issue and finding different interpretations for the error message like: MAIL command issued after BDAT command so it says Bad sequence of commands. But actually the problem was sorted when I changed my code above to
SmtpClient smtp = new SmtpClient();
smtp.UseDefaultCredentials = false; // <<<you need THIS
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "my user name";
NetworkCred.Password = "my password";
smtp.Credentials = NetworkCred;
smtp.Host = "my company mail site";//host of your mail account
smtp.Port = 2525;//port no of your mail account
smtp.Timeout = 500000;
smtp.Send(mm);
Notice that UseDefaultCredentials is set to false before the Credentials are assigned new credentials. This change of sequence of setting default to false magically worked for me.
Just for the record Network Solution SMTP seems to NEED the username in lowercase.
Why? Just cuz, that's why.
Hope it helps.. took me a very long time to figure it out..
Pat NH USA
If you are trying to send the mail from a different server (may be from your localhost) then this error comes, so if you want to test your smtp mail code you need to upload your code to your remote server and test (plesk server in my case) then it will work.
The answer by #puneet that mentions smtp.UseDefaultCredentials = false got us on the right track.
But our case was slightly different. We also got error Bad sequence of commands. The server response was: You must authenticate first (#5.5.1) but it only happened on password resets using the Password Recovery web part built in to ASP.NET Membership.
The Password Recovery web part relies on a web.config section called <mailSettings> so we changed defaultCredentials="true" to defaultCredentials="false" in web.config
<mailSettings>
<smtp deliveryMethod="Network" from="donotreply#someone.net">
<network defaultCredentials="false" host="mail.someone.net" userName="notifier#someone.net" password="password" port="587" />
</smtp>
And this fixed the error with Password Reset. Basically this is the same fix as #puneet but in a different location.
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(System.Configuration.ConfigurationSettings.AppSettings["smtp"]);
//code by cv 8july2014
mailClient.UseDefaultCredentials = false; // <<<you need THIS
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "username";
NetworkCred.Password = "Pasword";
mailClient.Credentials = NetworkCred;
// mailClient.Host = "my company mail site";//host of your mail account
mailClient.Port = 2525;
// mailMsg = null;
//SmtpMail.SmtpServer = System.Configuration.ConfigurationSettings.AppSettings["smtp"];
while (counter < 3)
{
try
{
mailClient.Send(mailMsg);
Thread.Sleep(2000);
counter = 3;
mailMsg = null;
}
catch (Exception ex)
{
counter = counter + 1;
if (counter == 2)
{
throw ex;
counter = 0;
}
}
}
Does .NET 4 has any problems in sending emails? I had a .NET 3.5 solution and it was working then migrated the solution to .NET 4 and It does not works; nothing changed!
Notes:
I get this exception:
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at ...
And this is my code:
public static void SendEmail(
this Email email)
{
if (email.MailingSettings == null) throw new ArgumentNullException("email.MailingSettings", "specify email.MailingSettings");
var settings = email.MailingSettings;
if (string.IsNullOrEmpty(email.Sender)) throw new ArgumentException("email.Sender", "specify a sender");
if (email.Recipients == null) throw new ArgumentNullException("email.Recipients", "specify at least a recipient");
if (email.Recipients.Length == 0) throw new ArgumentNullException("email.Recipients", "specify at least a recipient");
if (string.IsNullOrEmpty(settings.SMTPHost)) throw new ArgumentException("email.SMTPHost", "specify email.SMTPHost");
var mail = new MailMessage();
if (string.IsNullOrEmpty(email.SenderDisplayName))
mail.From = new MailAddress(email.Sender);
else
mail.From = new MailAddress(email.Sender, email.SenderDisplayName);
if (!string.IsNullOrEmpty(email.ReplyTo))
{
if (string.IsNullOrEmpty(email.ReplyToDisplayName))
{
mail.ReplyToList.Add(new MailAddress(email.ReplyTo));
}
else
{
mail.ReplyToList.Add(new MailAddress(email.ReplyTo, email.ReplyToDisplayName));
}
}
foreach (string recipient in email.Recipients)
mail.To.Add(new MailAddress(recipient));
mail.Subject = email.Subject;
mail.Body = email.Body;
mail.IsBodyHtml = settings.IsBodyHtml;
if (email.CC != null && email.CC.Length > 0)
foreach (string cci in email.CC)
mail.CC.Add(cci);
if (email.BCC != null && email.BCC.Length > 0)
foreach (string bcci in email.BCC)
mail.Bcc.Add(bcci);
if (email.Attachments != null)
foreach (var ifn in email.Attachments)
mail.Attachments.Add(
new Attachment(
new MemoryStream(
ifn.Content),
ifn.FileName));
var smtpPort = settings.SMTPPort > 0 ? settings.SMTPPort : 25;
var smtpClient = new SmtpClient(settings.SMTPHost, smtpPort);
smtpClient.EnableSsl = settings.EnableSsl;
if (!string.IsNullOrEmpty(settings.SMTPUser))
{
smtpClient.UseDefaultCredentials = false;
var smtpPassword = settings.SMTPPassword == null ? string.Empty : settings.SMTPPassword;
NetworkCredential netCred;
if (string.IsNullOrEmpty(settings.SMTPDomain))
netCred = new NetworkCredential(settings.SMTPUser, smtpPassword);
else
netCred = new NetworkCredential(settings.SMTPUser, smtpPassword, settings.SMTPDomain);
smtpClient.Credentials = netCred;
}
else
smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
smtpClient.Timeout = 180 * 1000;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
smtpClient.Send(mail);
}
If everything is as per posted-code and comments then I can say that you've turned on 2-step verification of your google account and in that case you need to generate Application Specific-password.
This code is correct and works. The problem was on GMail side and solved (not detected why and how).
Try to use this :
try
{
string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "senderemail#gmail.com";
string password = "password";
string emailTo = "receiver#gmail.com";
string subject = "Halo!";
string body = "Halo, Mr. SMTP";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
*Note before that you need to activated this : https://myaccount.google.com/lesssecureapps
and then build and run the code.. it's amazing.. :)