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.
Related
I'm developing a third-party add-on to run in a program called M-Files.
The purpose of the add-on is to send a mail with the help of an SMTP server. I created a fake SMTP server in DevelMail.com just for testing.
Testing the SMTP server from a browser works but when i run the code it gives me the following error.
Transaction failed. The server response was: 5.7.1 Client host rejected: Access denied
Here are the SMTP information:
Host: smtp.develmail.com
SMTP Port: 25
TLS/SSL Port: 465
STARTTLS Port : 587
Auth types: LOGIN, CRAM-MD5
Here is the code:
MailAddress adressFrom = new MailAddress("notification#mfiles.no", "M-Files Notification Add-on");
MailAddress adressTo = new MailAddress("majdnakhleh#live.no");
MailMessage message = new MailMessage(adressFrom, adressTo);
message.Subject = "M-Files Add-on running";
string htmlString = #"<html>
<body>
<p> Dear customer</p>
<p> This is a notification sent to you by using a mailadress written in a metadata property!.</p>
<p> Sincerely,<br>- M-Files</br></p>
</body>
</html>
";
message.Body = htmlString;
SmtpClient client = new SmtpClient();
client.Host = "smtp.develmail.com";
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential("myUserName", "myPassword");
client.EnableSsl = true;
client.Send(message);
Reason for the Issue:
Usually, email sending option using SMTP encountered Access denied
because there should have a sender email which required to allow
remote access. When SMTP request sent from the sender email
it checks whether there is remote access allowed. If no, then you
always got Access denied message.
Solution:
For example let's say, you want to send email using Gmail SMTP in that case you do have to enable Allow less secure apps: ON
How To Set
You can simply browse this link Less secure app access and turn that to ON
See the screen shot
Code Snippet:
public static object SendMail(string fromEmail, string toEmail, string mailSubject, string mailBody, string senderName, string senderPass, string attacmmentLocationPath)
{
try
{
MailMessage mail = new MailMessage();
//Must be change before using other than gmail smtp
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(fromEmail);
mail.To.Add(toEmail);
mail.Subject = mailSubject;
mail.Body = mailBody;
mail.IsBodyHtml = true;
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(senderName, senderPass);//Enter the credentails from you have configured earlier
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
return true;
}
catch (Exception ex)
{
return ex;
}
}
Note: Make sure, fromEmail and (senderName, senderPass) should be same email with the credential.
Hope that would help.
I have a piece of code sending out account activation emails with a link in it using SMTP. My code connects to my mail box on an email provider and sends out mails. The first few mails went through. And then they started failing. Obviously they were blocked as spams.
My question is then how can I test my code? People suggest to alter the configurations of the mail server. But since I am using a 3rd party email provider, I have no control over it.
My website production server is on AWS but I can't use that for my testing.
Here is a snippet of my code. Pretty standard.
using (var msg = new MailMessage())
{
msg.From = new MailAddress(From);
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = true;
msg.To.Add(toEmail);
string error = "";
try
{
using (var client = new SmtpClient(SMTPServer))
{
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(SMTPUserName, SMTPPassword);
client.Send(msg);
}
}
catch (SmtpFailedRecipientException se)
{
error = $"Unable to mail to {toEmail}";
}
catch (SmtpException se)
{
error = "Mail server connection failed.";
}
catch (Exception ex)
{
error = "Email failed";
}
return error;
}
SmtpException is thrown and no mails are sent/received.
The Subject is Blah blah Account Activation and the Body is Please use the following link to activate your account: <a href='blah blah blah'></a>.
I've been banging my head against this one for weeks, but today was the day I promised I'd get it fixed. So far I've failed.
I am trying to send an email from a hosted MVC application, via a Hosted Exchange server. The IT department has said and confirmed that they have allowed the IP of the MVC application through. However, the following code gives me "An attempt was made to access a socket in a way forbidden by its access permissions ###.###.###.###:25" every time.
ActionResult Test()
{
MailMessage message = new MailMessage();
message.From = new MailAddress("valid.email.address");
message.Subject = "Test Email";
message.To.Add(new MailAddress("another.valid.email.address"));
message.Body = "Hey, this is a test!";
using (SmtpClient client = new SmtpClient())
{
client.Credentials = new System.Net.NetworkCredential("username", "password");
client.Port = 25;
client.EnableSsl = true; // Either true or false gives same result
client.Host = "actual.host.url";
try
{
client.Send(message);
}
catch (Exception ex)
{
ViewBag.LogMessage = string.Format("Error: {0}<br />{1}<br />{2}", ex.Message, ex?.InnerException.Message, ex?.InnerException?.InnerException.Message);
return View();
}
ViewBag.LogMessage = string.Format("client.Host: {0}<br />Client.Port: {1}<br />Client.EnableSsl: {2}<br />message.To[0].Address: {3}", client.Host, client.Port, client.EnableSsl ? "true" : "false", message.To[0].Address);
}
return View();
}
The value of the LogMessage is:
Error: Failure sending mail.
Unable to connect to the remote server
An attempt was made to access a socket in a way forbidden by its access permissions ###.###.###.###:25
Any suggestions would be welcome! I've tried port 587 with no luck. I've tried with and without credentials, with or without SSL, username matching from address or not. I've run out of things to try.
Thanks!
Try the following code, the first line tells SMTP Client to ignore any issue with the SSL cert if its provide from an invalid provider.
ServicePointManager.ServerCertificateValidationCallback =(sender,certificate, chain, sslPolicyErrors) => true;
var smtpClient = new SmtpClient("oba.exchangeserver.com")
{
Port = 587,
EnableSsl = true,
Credentials =
new NetworkCredential("username","password")
};
return smtpClient;
I should mention this is just a learning project, and will never be hosted online. I am running the app locally.
I'm having two problems sending email with parameters passed in:
The main problem: it doesn't send.
The parameters don't populate the form in the view until after clicking send and redirecting to the same page, however they are displaying in the URL.
Here is my code:
Mail.cs (Model)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LotManager.Models
{
public class Mail
{
public string From = "myusername#gmail.com";
public string To { get; set; }
public string Subject = "Parking Alert";
public string Body { get; set; }
}
}
MailController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using LotManager.Controllers;
namespace LotManager.Controllers
{
public class MailController : Controller
{
//
// GET: /SendMailer/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ViewResult Index(LotManager.Models.Mail _objModelMail)
{
var to = Request.QueryString["To"];
ViewBag.To = to;
var body = Request.QueryString["Body"];
ViewBag.Body = body;
if (ModelState.IsValid)
{
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(_objModelMail.From);
string Body = body;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("mygmailusername", "mypassword"); //My actual account info goes here
smtp.EnableSsl = true;
try
{
smtp.Send(mail);
}
catch (Exception)
{
Console.WriteLine("The email was not sent, because I couldn't get it to work. Oops!");
}
return View("Index", _objModelMail);
}
else
{
return View();
}
}
}
}
Index.cshtml (Send Mail View)
#model LotManager.Models.Mail
#{
ViewBag.Title = "Send";
}
<h2>Send</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary()
<p>To: </p>
<p>#Html.TextBoxFor(m => m.To, new { #Value = #ViewBag.To })</p>
<p>Body: </p>
<p>#Html.TextBoxFor(m => m.Body, new { #Value = #ViewBag.Body })</p>
<input type="submit" value="Send" />
}
The code that passes the parameters to the URL:
#Html.Actionlink("Send Notification", "Index", "Mail", new { To = item.Employee.Email, Body = item.Description }, null)
A malicious user can use your page to spam people using your email account. That will quickly destroy your sender reputation with Gmail. It can be nearly impossible to recover from a badly tarnished sender reputation.
Issue 1
You're using the wrong SMTP port.
smtp.gmail.com requires port 465 for SSL or port 587 for TLS.
Issue 2
You are invoking the controller using a link (ActionLink), which creates a GET request. Your controller action will only be invoked for a POST however due to the [HttpPost] attribute. Either remove [HttpPost], or use a post action rather than a link to invoke the controller action.
The parameters are nor avialliable, becasue You are using [HttpPost]. Paramters are visible in GET not in POST.
About second problem look at Google documentation: https://support.google.com/a/answer/176600?hl=en
If you want to use port 25 you need to change server to smtp-relay.gmail.com. Otherwise change port to 465 for SSL or port 587 for TLS.
I am stuck and not able to receive email from yahoo id(if the sender email id is of yahoo).
code is working fine not giving me any error and i am receiving email fromm gmail id.
i am using localhost (not in local machine on live server).
hosting server : smtp.snapgrid.com
also used authentication,enable ssl , using proper port for ssl.
on snapgrid i do check so i got is mail from yahoo is blocked and the message is,
message :
Type: blocked
Reason: 550 5.7.1 Unauthenticated email from yahoo.com is not accepted due to domain's
DMARC policy. Please contact administrator of yahoo.com domain if this was a legitimate
mail. Please visit http://support.google.com/mail/answer/2451690 to learn about DMARC
initiative.
please help...
code i used to send is(its working fine just giving for idea):
Method 1:
SmtpClient objSMTPClient = new SmtpClient();
objSMTPClient.Host = ConfigurationManager.AppSettings["strSMTPServer"];
string BODY_FORMAT = ConfigurationManager.AppSettings["EmailBodyContentFormat"];
MailMessage objMailMessage = new MailMessage(from.Trim(), to.Trim(), subject.Trim(), body.Trim());
objSMTPClient.UseDefaultCredentials = false;
if (BODY_FORMAT.ToUpper() == "HTML")
objMailMessage.IsBodyHtml = true;
else if (BODY_FORMAT.ToUpper() == "TEXT")
{
body = StripTags(body);
objMailMessage.IsBodyHtml = false;
objMailMessage.Body = body.ToString().Trim();
}
else
return false;
objSMTPClient.Send(objMailMessage);
return true;
Method 2:
SmtpClient oMail = new SmtpClient();
MailMessage msg = new MailMessage();
MailAddress Madd = new MailAddress(from, "sunil");
oMail.Host = "smtp.gmail.com";
oMail.Port = 587;
oMail.EnableSsl = true;
oMail.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
oMail.Credentials = new NetworkCredential("sunil123#mydomain.com", "******");
oMail.Timeout = 20000;
msg.From = Madd;
msg.Body = body.ToString();
msg.To.Add(to);
msg.Subject = subject;
msg.IsBodyHtml = true;
oMail.Send(msg);
return true;
both are working having no bug running without error....
If you are sending via a server belonging to someone like Yahoo, Google or Office365 they expect the sender name of the account to match that that you're sending using in the from address.
For example, this would work on a your local SMTP server:
Message.From = new MailAddress("GrandMasterFlush#domain.com");
However, to get it to send via someone like Yahoo would require you to send it like this:
Message.From = new MailAddress("GrandMasterFlush#domain.com", "Grandmaster Flush");
If the sender name provided does not exactly match that of the account the email will not get sent.