I'd like to create a web application in ASP.NET C# MVC 5 using Parallels Plesk Panel 11.5 using HostGator.
Is that possible? I'd like my web app to send an email whenever someone fills out a particular form. Where can I go to find out the SMTP server information? What do I need to know to set that up?
I'd appreciate any other help, links, or guides you can provide as I set this up.
Thank you.
This is might be too late but to help the others;
public static void SendEmail(string toEmail, string subject, string body)
{
try
{
const string fromEmail = "yourEmail#YourDomain.com";
var message = new MailMessage
{
From = new MailAddress(fromEmail),
To = { toEmail },
Subject = subject,
Body = body,
DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
};
using (SmtpClient smtpClient = new SmtpClient("webmail.YourDomain.com"))
{
smtpClient.Credentials = new NetworkCredential("yourEmail#YourDomain.com", "your email password");
smtpClient.Port = 25;
smtpClient.EnableSsl = false;
smtpClient.Send(message);
}
}
catch (Exception excep)
{
//ignore it or you can retry .
}
}
This worked for me on Plesk Onyx 17.5.3
Related
Below is the code I'm using. Please advise on how this can be rectified.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Net.Mail;
public partial class mailtest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SendEmail(object sender, EventArgs e)
{
lblmsg.Text = "";
try
{
using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
{
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
//if (fuAttachment.HasFile)
//{
// string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
// mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
//}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = txtsmtphost.Text.Trim();
smtp.EnableSsl = false;
if (chkssl.Checked == true)
{
smtp.EnableSsl = true;
}
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(txtport.Text);
smtp.Send(mm);
lblmsg.ForeColor = System.Drawing.Color.DarkGreen;
lblmsg.Text = "Email sent successfuly !!";
//ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent successfuly !!');", true);
}
}
catch (Exception ex)
{
lblmsg.ForeColor = System.Drawing.Color.Red;
lblmsg.Text = "Failed " + ex.ToString();
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Failed');", true);
}
}}
The error message is:
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 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, MailAddress from, Boolean allowUnicode) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message)
Since this question keeps coming up as the first on Google, what today worked for me (11 June 2022) is what I will share. This question has been asked many times in similar way and many different things have worked for many people, but that stops now, there are no work around in "code" anymore (assuming your code is perfect but throwing exception as written in the title above)! Why because Google made a change (from https://support.google.com/accounts/answer/6010255):
Less secure apps & your Google Account:
To help keep your account secure, from May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.
Important: This deadline does not apply to Google Workspace or Google Cloud Identity customers. The enforcement date for these customers will be announced on the Workspace blog at a later date.
Now what do you do, its simpler then you think, go to https://myaccount.google.com/, Click "Security", enable Two-step Verification, once done, come back to the myaccount Security page, you will see "App passwords", open that, it will give you options for what you are trying to make a password for (a bunch of devices), select "Windows Computer", make a password, copy it, use this password in the NetworkCredential class object in your code, and your emails should start working again through Code.
This wasted so much of my hours yesterday, my Winforms app was working perfect till a couple days back it stopped sending emails.
The SMTP server requires a secure connection or the client was not authenticated.
To fix this error Go to your google account and generate an apps password
When running your code use the password generated instead of the actual users password.
This happens most often when the account has 2fa enabled.
Example with SmtpClient
using System;
using System.Net;
using System.Net.Mail;
namespace GmailSmtpConsoleApp
{
class Program
{
private const string To = "test#test.com";
private const string From = "test#test.com";
private const string GoogleAppPassword = "XXXXXXXX";
private const string Subject = "Test email";
private const string Body = "<h1>Hello</h1>";
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new NetworkCredential(From , GoogleAppPassword),
EnableSsl = true,
};
var mailMessage = new MailMessage
{
From = new MailAddress(From),
Subject = Subject,
Body = Body,
IsBodyHtml = true,
};
mailMessage.To.Add(To);
smtpClient.Send(mailMessage);
}
}
}
You should enable the less secure app settings on the Gmail account you are using to send emails. You can use this Link to enable the settings.
More information about your problem here.
I'm trying to send email using C# code, email was sent when I send it to single person but it is not getting sent when I send it to multiple persons. and getting an error "The operation has timed out." I'm not getting the reason behind it. Please help to find the reason.
Code:
public string SendEmail(List<string> ToEmailAddresses,string body, string emailSubject)
{
var smtp = new SmtpClient { DeliveryMethod = SmtpDeliveryMethod.Network };
smtp.Host = "xyz-host-name";
smtp.Port = 25;
smtp.EnableSsl = false;
var fromAddress = new MailAddress(ConfigurationManager.AppSettings["MailUserName"], "Rewards and Recognition Team");
using (var message = new MailMessage() { Subject = emailSubject, Body = body })
{
message.From = fromAddress;
foreach (string email in ToEmailAddresses)
{
message.To.Add(email);
}
message.IsBodyHtml = true;
try
{
_logger.Log("EmailService-SendEmail-try");
smtp.Send(message);
return "Success";
}
catch (Exception ex)
{
_logger.Log("EmailService-SendEmail-" + ex.Message);
return "Error";
}
}
}
Whenever you're attempting to do anything which may take some time, it's always best practice to run it in a separate thread or use an asynchronous method.My recommendation would be to use the SmtpClient.SendAsync method. To do this, change:
public string SendEmail(List<string> ToEmailAddresses, string body, string emailSubject)
to:
public async string SendEmail(List<string> ToEmailAddresses, string body, string emailSubject)
and include await smtp.SendAsync(...) rather than smtp.Send(...). This will allow further execution of the UI thread whilst sending the mail and not make the application grey out with the "not responding" message.To read more about smtp.SendAsync(...) including parameters and remarks, take a look at the MSDN documentation regarding the method.
i'm try to send some simple email to for example test#blabla.com
First of all, I've already tried it in my Localhost, and it worked, the problem was when i uploaded it to my Server
the Server i'm using is windows server 2012 R2, with IIS 7 (not really sure with the version but i believe it's 7 and above)
hosted successfully with no problem, just the send email method don't work...
I've already add SMTP feature, set the SMTP E-MAIL(Yes, there are no SMTP Virtual server in IIS 7 and above)
here's my controller
public ActionResult SendTestEmail()
{
var test_address = "test#blabla.com";
try
{
// Initialize WebMail helper
WebMail.SmtpServer = "localhost";
WebMail.SmtpPort = 25; // Or the port you've been told to use
WebMail.EnableSsl = false;
WebMail.UserName = "";
WebMail.Password = "";
WebMail.From = "admin#testserver.com"; // random email
WebMail.Send(to: test_address,
subject: "Test email message",
body: "This is a debug email message"
);
}
catch (Exception ex)
{
ViewBag.errorMessage = ex.Message; // catch error
}
return View();
}
here is my SMTP E-mail settings:
the error message are: Mailbox unavailable. The server response was: 5.7.1 Unable to relay for test#blabla.com (this happens when i leave the E-mail address textbox empty, this also happens when i've entering any email format such as sample#email.com / my primary e-mail)
You need to set your smtp settings to a real smtp server....
Try some smtp servers off this list if you don't have access to your own...
Here's a nice bit of code for you... Taken from here
MailModel.cs
public class MailModel
{
public string From { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
SendMailerController.cs - Notice where the smtp settings are stated
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
namespace SendMail.Controllers
{
public class SendMailerController : Controller
{
// GET: /SendMailer/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ViewResult Index(SendMail.Models.MailModel _objModelMail)
{
if (ModelState.IsValid)
{
MailMessage mail = new MailMessage();
mail.To.Add(_objModelMail.To);
mail.From = new MailAddress(_objModelMail.From);
mail.Subject = _objModelMail.Subject;
string Body = _objModelMail.Body;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("username", "password");// Enter senders User name and password
smtp.EnableSsl = false;
smtp.Send(mail);
return View("Index", _objModelMail);
}
else
{
return View();
}
}
}
}
Index.cshtml
#model SendMail.Models.MailModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<fieldset>
<legend>Send Email</legend>
#using (Html.BeginForm())
{
#Html.ValidationSummary()
<p>From: </p>
<p>#Html.TextBoxFor(m=>m.From)</p>
<p>To: </p>
<p>#Html.TextBoxFor(m=>m.To)</p>
<p>Subject: </p>
<p>#Html.TextBoxFor(m=>m.Subject)</p>
<p>Body: </p>
<p>#Html.TextAreaFor(m=>m.Body)</p>
<input type ="submit" value ="Send" />
}
</fieldset>
UPDATE
How to setup SMTP server on IIS7
start->administrative tools->server manager, go to features, select "add features", tick "smtp server" (if it is not already installed), choose to install the required "remote server admin toos"
check to confirm that "Simple Mail Transfer Protocol (SMTP)" service is running, if so, we are good to go.
start->administrative tools>internet info services(iis) 6.0
make sure that SMTP virtual server/default smtp server is running, if not, right click, then choose "start"
in IIS7, go to website/virtual directory, double click "SMTP E-mail", Click on "Deliver e-mail to SMTP server", check the "Use localhost" checkmark
Why not try to use gmail for email sender? It's easy to use.
I always just build simple method
public void SendEmail()
{
MailMessage mail = new MailMessage("xxx#gmail.com", "sendTo", "mailSubject", "mailBody");
mail.From = new MailAddress("xxx#gmail.com", "nameEmail");
mail.IsBodyHtml = true; // necessary if you're using html email
NetworkCredential credential = new NetworkCredential("xxx#gmail.com", "xxxxx");
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = credential;
smtp.Send(mail);
}
Just use async/await if you want wait the email sent.
This question already has answers here:
Sending email through Gmail SMTP server with C#
(31 answers)
Closed 9 years ago.
I am New in Asp.net, i need to send email from Asp.net using my Outlook.
I have one button in asp and when i click button(send) i want to send email.
I tried to use Hotmail and Gmail but remote server in blocked.
If you don't understand my question please tell me.
I tried this:
var smtpClient = new SmtpClient
{
Host = "outlook.mycompany.local",
UseDefaultCredentials = false,
Credentials = new NetworkCredential("myEmail#mycommpany.com", "myPassword")
};
var message = new System.Net.Mail.MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("myemail#mycommapny.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("friendEmail#Company.com"));
// and here you're actually sending the message
smtpClient.Send(message);
}
Exeption Show: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated
Please how can i do that ?
Sending outbound email from an ASP.net web site can be problematic. Even if you get the SMTP information right, you still have to deal with:
Sender Policy Framework (SPF)
Whitelists/Blacklists
Validation
Bouncebacks
It's very difficult to do this yourself, which is why you might want to consider using a service provider instead. You simply use their API (often a REST call), and they do the rest. Here are three such providers:
SendGrid
Mandrill
Mailgun
Mandrill has a low-end free plan, and so does SendGrid if you are using it with Windows Azure. And they are all reasonably affordable, even for the larger plans.
I highly recommend using one of these with their own API instead of using System.Net.Mail yourself. But if you want, they also can act as an SMTP relay for you so you can use their SMTP servers and keep your System.Net.Mail code intact.
First of all get the company SMTP server settings (from your sys admins I guess), then you can do something like this:
// setting up the server
var smtpClient = new SmtpClient
{
Host = "your.company.smtp.server",
UseDefaultCredentials = false,
EnableSsl = true, // <-- see if you need this
Credentials = new NetworkCredential("account_to_use", "password")
};
var message = new MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("from#company.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("neo#matrix.com"));
// and here you're actually sending the message
smtpClient.Send(message);
you can use this function. and one thing you have to store you email smtp login and password in web config file
/// <summary>
/// Send Email
/// </summary>
/// <param name="strFrom"></param>
/// <param name="strTo"></param>
/// <param name="strSubject"></param>
/// <param name="strBody"></param>
/// <param name="strAttachmentPath"></param>
/// <param name="IsBodyHTML"></param>
/// <returns></returns>
public Boolean sendemail(String strFrom, string strTo, string strSubject, string strBody, string strAttachmentPath, bool IsBodyHTML)
{
Array arrToArray;
char[] splitter = { ';' };
arrToArray = strTo.Split(splitter);
MailMessage mm = new MailMessage();
mm.From = new MailAddress(strFrom);
mm.Subject = strSubject;
mm.Body = strBody;
mm.IsBodyHtml = IsBodyHTML;
//mm.ReplyTo = new MailAddress("replyto#xyz.com");
foreach (string s in arrToArray)
{
mm.To.Add(new MailAddress(s));
}
if (strAttachmentPath != "")
{
try
{
//Add Attachment
Attachment attachFile = new Attachment(strAttachmentPath);
mm.Attachments.Add(attachFile);
}
catch { }
}
SmtpClient smtp = new SmtpClient();
try
{
smtp.Host = ConfigurationManager.AppSettings["MailServer"].ToString();
smtp.EnableSsl = true; //Depending on server SSL Settings true/false
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["MailUserName"].ToString();
NetworkCred.Password = ConfigurationManager.AppSettings["MailPassword"].ToString();
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;//Specify your port No;
smtp.Send(mm);
return true;
}
catch
{
mm.Dispose();
smtp = null;
return false;
}
}
Try Amazon Simple Email Service (http://aws.amazon.com/ses/). If you're new to Amazon Web Services (AWS) there might be a learning curve. However, once you're familiar with their SDK which can be found on Nuget (AWSSDK) the process is very straight-forward (Amazon does have a lot of little wrapper classes which can be quirky).
So, to answer the question "How to send email?", it looks something like:
var fromAddress = "from#youraddress.com";
var toAddresses = new Amazon.SimpleEmail.Model.Destination("someone#somedestination.com");
var subject = new Amazon.SimpleEmail.Model.Content("Message");
var body= new Body(new Amazon.SimpleEmail.Model.Content("Body"));
var message = new Message(subject , body);
var client = ConfigUtility.AmazonSimpleEmailServiceClient;
var request= new Amazon.SimpleEmail.Model.SendEmailRequest();
request.WithSource(fromAddress)
.WithDestination(toAddresses)
.WithMessage(message );
try
{
client.SendEmail(request);
}
catch (Amazon.SimpleEmail.AmazonSimpleEmailServiceException sesError)
{
throw new SupplyitException("There was a problem sending your email", sesError);
}
You can refer to below links:
http://www.codeproject.com/Tips/371417/Send-Mail-Contact-Form-using-ASP-NET-and-Csharp
send email asp.net c#
I hope it will help you. :)
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()