Send email through SMTP - c#

I have contact page on my website and I want users to enter Their name and email id (no password) and send email on button click.
I did Google and all solutions i am getting requires user password,
public static void SendMessage(string subject, string messageBody, string toAddress, string ccAddress, string fromAddress)
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
// Set the sender's address
message.From = new MailAddress(fromAddress);
// Allow multiple "To" addresses to be separated by a semi-colon
if (toAddress.Trim().Length > 0)
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
// Allow multiple "Cc" addresses to be separated by a semi-colon
if (ccAddress.Trim().Length > 0)
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
// Set the subject and message body text
message.Subject = subject;
message.Body = messageBody;
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtpHost";
smtp.Port =portno;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("fromEmail", "fromPassword");
smtp.Timeout = 20000;
}
// Send the e-mail message
smtp.Send(message);
}
But I don't want to force users to enter password. Is there any other solution using SMTP?
The error I am getting is A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

I have this function in my utility class , and it works like a charm.
public static bool SendMail(string Email, string MailSubject, string MailBody)
{
bool isSent = false, isMailVIASSL = Convert.ToBoolean(ConfigurationManager.AppSettings["MailServerUseSsl"]);
string mailHost = ConfigurationManager.AppSettings["MailServerAddress"].ToString(),
senderAddress = ConfigurationManager.AppSettings["MailServerSenderUserName"].ToString(),
senderPassword = ConfigurationManager.AppSettings["MailServerSenderPassword"].ToString();
int serverPort = Convert.ToInt32(ConfigurationManager.AppSettings["MailServerPort"]);
MailMessage msgEmail = new MailMessage(new MailAddress(senderAddress), new MailAddress(Email));
using (msgEmail)
{
msgEmail.IsBodyHtml = true;
msgEmail.BodyEncoding = System.Text.Encoding.UTF8;
msgEmail.Subject = MailSubject;
msgEmail.Body = MailBody;
using (SmtpClient smtp = new SmtpClient(mailHost))
{
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = isMailVIASSL;
smtp.Credentials = new NetworkCredential(senderAddress, senderPassword);
smtp.Port = serverPort;
try
{
smtp.Send(msgEmail);
isSent = true;
}
catch (Exception ex)
{
throw ex;
}
}
}
return isSent;
}
<!-- Mail Server Settings -->
<add key="MailServerAddress" value="smtp.gmail.com" />
<add key="MailServerPort" value="25" />
<add key="MailServerSenderUserName" value="username#gmail.com" />
<add key="MailServerSenderPassword" value="password" />
<add key="MailServerUseSsl" value="True" />

Related

C# receive error sending a email

ERROR: Service not available, closing transmission channel. The server response was: Resources temporarily unavailable - Please try again later
private void button1_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.mail.yahoo.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "mail#yahoo.com";
string password = "mailpass";
string emailTo = "sendemail#yahoo.com";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
//mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
// mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
//mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}
What should I do?
You need to make sure an external application has permission to send emails through your email before you can proceed.

Mail sending fails through c# when encryption connection is TLS

I am setting up mail sending in my code as below
NetworkCredential nc = new NetworkCredential(ConfigurationManager.AppSettings["EmailId"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
MailMessage mm = new MailMessage();
mm.From = new MailAddress(SendEmailaddress);
mm.Body = "Test Mail";
mm.IsBodyHtml = true;
mm.BodyEncoding = System.Text.Encoding.UTF8;
mm.To.Add(ToEmailAddress);
mm.Subject = "Test";
SmtpClient sp = new SmtpClient();
sp.UseDefaultCredentials = false;
sp.Credentials = nc;
sp.EnableSsl = true;
sp.DeliveryMethod = SmtpDeliveryMethod.Network;
sp.Port = 587
sp.Host = ConfigurationManager.AppSettings["SMTP"].ToString();
sp.Send(mm);
A error is thrown at the time of mail sending. Mail sending works if I configure outlook on the same PC with these settings with TLS as encrypted connnection.
I have checked many posts where it is suggested that EnableSsl = true should be set for TLS to work but it does not work for me. It throws below error
Transaction failed. The server response was: 5.7.1
: Recipient address rejected: Access denied
at System.Net.Mail.RecipientCommand.CheckResponse(SmtpStatusCode
statusCode, String response) at
System.Net.Mail.SmtpTransport.SendMail(MailAddress sender,
MailAddressCollection recipients, String deliveryNotify,
SmtpFailedRecipientException& exception) at
System.Net.Mail.SmtpClient.Send(MailMessage message)
I have hit a roadblock as no solution is found. is there a setting which needs to be done on server?
protected void SendAlertEmail(string smtpserver, string smtpport, string smtpuser, string smtppass, int ssl, int auth, string subject, string from, string to, string body)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(SplitEmailStrging(from), HttpUtility.HtmlDecode(Request.Form["senderName"]));
string emails = to;
if (emails.Contains(","))
{
string[] emailslist = Regex.Split(emails, #",");
foreach (string email in emailslist)
{
mail.To.Add(SplitEmailStrging(email));
}
}
else
{
if (emails.Contains("<"))
{
mail.To.Add(SplitEmailStrging(emails));
// Response.Write(SplitEmailStrging(emails));
}
else
{
mail.To.Add(emails);
// Response.Write(emails);
}
}
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = HttpUtility.HtmlDecode(body);
SmtpClient client = new SmtpClient(smtpserver);
if (int.Parse(smtpport) == 465)
{
client.Port = 25;
}
else
{
client.Port = int.Parse(smtpport);
}
if (ssl == 1)
{
client.EnableSsl = true;
}
else
{
client.EnableSsl = false;
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpuser, smtppass);
client.UseDefaultCredentials = false;
client.Credentials = credentials;
client.Send(mail);
}
catch (Exception ex)
{
Response.Write("Error: " + ex.InnerException.Message);
Response.End();
}
}

C# Customising MailAddress.From field not working

I am trying to send Emails from my custom address to users using C# and googles smtp service. My problem is that when the when the user receives the message it is displayed admin#customDomain.co.uk <myAddress#gmail.com> in the from section of the email.
My problem is that I want the user to see admin#customDomain.co.uk <admin#customDomain.co.uk>. Is this possible using the google service? Or should I look at some other option? If so what?
I have tried the answers on this thread but non worked and I also found this google blog post but I cant work out how it can solve my issue
My Code
string SmtpAddress = "smtp.gmail.com";
int MyPort = 587;
bool enableSSL = true;
string MyPassword = "somePassword";
string MyUsername = "aUsername";
public string EmailFrom = "admin#customDomain.co.uk";
public string Subject = "Test Subject";
public void Send(string body, BL.Customer customer)
{
using (MailMessage message = new MailMessage())
{
message.To.Add(new MailAddress(customer.EmailAddress));
if (!String.IsNullOrEmpty(customer.SCEmailAddress))
{
//message.To.Add(new MailAddress(customer.SCEmailAddress));
}
message.From = new MailAddress(EmailFrom, EmailFrom);
message.Subject = Subject;
message.Body = string.Format(body);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = MyUsername,
Password = MyPassword
};
smtp.Credentials = credential;
smtp.Host = SmtpAddress;
smtp.Port = MyPort;
smtp.EnableSsl = enableSSL;
try
{
smtp.Send(message);
}
catch (SmtpException se)
{
throw se;
}
}
}
}

Time out error while sending mail to gmail account using smtp port 465 in asp.net

public void SendEmailWithAttachment(string pFrom, string pTo, string pSubject, string pBody, string pServer, string strAttachmentPDFFileNames)
{
try
{
System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
string UserName = ConfigurationManager.AppSettings["SMTPUserName"];
string Password = ConfigurationManager.AppSettings["SMTPPassword"];
if (pTo.Contains(","))
{
string[] ToAdd = pTo.Split(new Char[] { ',' });
for (int i = 0; i < ToAdd.Length; i++)
{
Message.To.Add(ToAdd[i]);
}
}
else
{
Message.To.Add(pTo);
}
//System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(pTo);
//Message.To.Add(toAddress);
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress(pFrom);
Message.From = fromAddress;
Message.Subject = pSubject;
Message.Body = pBody;
Message.IsBodyHtml = true;
// Stream streamPDFImages = new MemoryStream(bytPDFImageFile);
//System.Net.Mail.SmtpClient
var smtpClient = new System.Net.Mail.SmtpClient();
{
Message.Attachments.Add(new System.Net.Mail.Attachment(strAttachmentPDFFileNames));
smtpClient.EnableSsl = true;
smtpClient.Host = pServer;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
smtpClient.Port = 465;
smtpClient.Send(Message);
}
}
catch (Exception Exc)
{
Exception ex = new Exception("Unable to send email . Please Contact administrator", Exc);
throw ex;
}
}
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("yourMail", "yourPassword");
smtp.EnableSsl = true;
MailMessage msg = new MailMessage(sendFrom, "yourMail");
msg.ReplyToList.Add(sendFrom);
msg.Subject = subject;
msg.Body = bodyTxt;
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(#"C:\Projects\EverydayProject\test.txt");
msg.Attachments.Add(attachment);
smtp.Send(msg);
Here is working code to send an email to gmail smtp. From what I see you don't set UseDefaultCredentials = false and you are using wrong port. Also you MUST NOT override exceptions like this., throw the initial exception. Also for this to work you need to turn off security setting in your Gmail account. You can google it.

Sending an email programmatically through an SMTP server

Trying to send an email through an SMTP server, but I'm getting a nondescript error on the smtp.Send(mail); snippet of code.
Server side, the relay IP addresses look correct. Scratching my head about what I'm missing.
MailMessage mail = new MailMessage();
mail.To.Add(txtEmail.Text);
mail.From = new MailAddress("no-reply#company.us");
mail.Subject = "Thank you for your submission...";
mail.Body = "This is where the body text goes";
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "mailex.company.us";
smtp.Credentials = new System.Net.NetworkCredential
("AdminName", "************");
smtp.EnableSsl = false;
if (fileuploadResume.HasFile)
{
mail.Attachments.Add(new Attachment(fileuploadResume.PostedFile.InputStream,
fileuploadResume.FileName));
}
smtp.Send(mail);
Try adding smtp.DeliveryMethod = SmtpDeliveryMethod.Network; prior to send.
For reference, here is my standard mail function:
public void sendMail(MailMessage msg)
{
string username = "username"; //email address or domain user for exchange authentication
string password = "password"; //password
SmtpClient mClient = new SmtpClient();
mClient.Host = "mailex.company.us";
mClient.Credentials = new NetworkCredential(username, password);
mClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mClient.Timeout = 100000;
mClient.Send(msg);
}
Typically called something like this:
MailMessage msg = new MailMessage();
msg.From = new MailAddress("fromAddr");
msg.To.Add(anAddr);
if (File.Exists(fullExportPath))
{
Attachment mailAttachment = new Attachment(fullExportPath); //attach
msg.Attachments.Add(mailAttachment);
msg.Subject = "Subj";
msg.IsBodyHtml = true;
msg.BodyEncoding = Encoding.ASCII;
msg.Body = "Body";
sendMail(msg);
}
else
{
//handle missing attachments
}
var client = new SmtpClient("smtp.gmail.com", 587);
Credentials = new NetworkCredential("sendermailadress", "senderpassword"),
EnableSsl = true
client.Send("sender mail adress","receiver mail adress", "subject", "body");
MessageBox.Show("mail sent");
This is Adil's answer formatted for C#:
public static class Email
{
private static string _senderEmailAddress = "sendermailadress";
private static string _senderPassword = "senderpassword";
public static void SendEmail(string receiverEmailAddress, string subject, string body)
{
try
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential(_senderEmailAddress, _senderPassword),
EnableSsl = true
};
client.Send(_senderEmailAddress, receiverEmailAddress, subject, body);
}
catch (Exception e)
{
Console.WriteLine("Exception sending email." + Environment.NewLine + e);
}
}
}
You didn't specify the port.
smtp.Port = 1111; // whatever port your SMTP server uses
The SMTP has three different "standard" ports: 25, 465 and 587. According to msdn documentation, the default value for the Port property is 25.

Categories