When I run my application locally on localhost, the e-mail is sent out successfully with no exceptions. But when I publish the application and try to re-create the e-mail it does not send the e-mail nor sends the View with the corresponding error.
try
{
using (var mail = new MailMessage())
{
const string email = "*******#gmail.com";
const string password = "*********";
var loginInfo = new NetworkCredential(email, password);
mail.From = new MailAddress("*******#gmail.com");
mail.To.Add(new MailAddress("email#email.com"));
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
try
{
using (var smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(mail);
}
}
finally
{
mail.Dispose();
}
}
}
catch (SmtpFailedRecipientsException ex)
{
foreach (SmtpFailedRecipientException t in ex.InnerExceptions)
{
var status = t.StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
return View(status);
}
else
{
return View(status);
}
}
}
catch (SmtpException Se)
{
// handle exception here
return View(Se);
}
catch (Exception ex)
{
return View(ex);
}
The error message is not displayed here, however, it is possible that is a client authentication error.
Please try:
Login into your gmail account
Allow the IP of your hosting under gmail settings
Retry sending the email
Another thing to note, you do not need to try .. finally on your MailMessage() object. Since it is already wrapped in a using statement, when it reaches the end of the using block is will dispose it for you and any errors will get caught in your outer try catch block.
Remove all that exception handling, and try again. Find out what the error is, then go from there.
I suspect the reason youre having a hard time is b/c of the way you have your try/catch's set up. The inner try/catch strikes me as being a little odd.
Related
I am unable to connect to the frontier mail server with the following code. I get the message "Unable to connect to remote server". I am running the program using C# on my local computer.
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.frontier.com");
mail.From = new MailAddress(emailaddress);
mail.To.Add("xxxx#frontier.com");
mail.Subject = thistitle;
mail.Body = thisdescription;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(thisimage);
mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "xxxxxxx");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("Mail sent");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Email Error Message");
}
Can anyone tell if I have the correct parameters for Frontier mail? I know they use Yahoo but I tried that also with no success. Isn't it possible to run a mail server from my local machine? Any help is appreciated.
just try remove this code SmtpServer.EnableSsl = true;
Does your ISP block SMTP traffic? (this is often the case for non-commercial accounts).
If not... rewrite you code closer to this:
try
{
using (var attachment = new Attachment(thisimage))
using (var mail = new MailMessage())
{
mail.From = new MailAddress(emailaddress);
mail.To.Add("xxxx#frontier.com");
mail.Subject = thistitle;
mail.Body = thisdescription;
mail.Attachments.Add(attachment);
using (var client = new SmtpClient("smtp.frontier.com"))
{
client.Port = 25;
client.Credentials = new System.Net.NetworkCredential("username", "xxxxxxx");
client.EnableSsl = true;
client.Send(mail);
}
}
MessageBox.Show("Mail sent");
}
catch (SmtpException ex)
{
// go read through https://msdn.microsoft.com/en-us/library/swas0fwc(v=vs.110).aspx
// go read through https://msdn.microsoft.com/en-us/library/system.net.mail.smtpexception(v=vs.110).aspx
}
#if DEBUG
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Email Error Message");
}
#endif
}
...and run it in a debugger and look at what the SmtpException is reporting. There are myriad reasons why you may fail a connection.
Im unable to comment so I will type my comment as an answer. Are you able to use ImapClient instead of SmtpClient ? With Imap, you can do some authenticating processes. Could be the issue, it only looks like you are signing in. For Imap I do this:
using (var clientTest = new ImapClient())
{
clientTest.Connect("xxxx#frontier.com");
clientTest.AuthenticationMechanisms.Remove("XOAUTH");
clientTest.Authenticate(eMail, pw);
bIsConnected = clientTest.IsConnected;
if (bIsConnected == true)
{
/// Insert Code here
}
}
I am using the following code in order to send emails. The emails are received successfully to the recipients at works but they are not received outside. I tried to send an email to my gmail account and same issue, I cannot received it.
At work, we are using Exchange 2010. I checked junk in gmail and no emails were found.
My Code:
public bool SendEmail()
{
try
{
var mailMessage = CreateMailMessage();
var client = new SmtpClient()
{
Credentials = new NetworkCredential(Resources.Username, Resources.Password, Resources.Domain),
Port = 25,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Host = ConfigurationProperties.ExchangeIPAddress
};
client.Send(mailMessage);
}
catch (Exception ex)
{
LogFile.Write(string.Format("EmailManager::SendEmail failed at {0}", DateTime.Now.ToLongTimeString()));
LogFile.Write(string.Format("Error: {0}", ex.Message));
return false;
}
return true;
}
private MailMessage CreateMailMessage()
{
var mailMessage = new MailMessage();
mailMessage.Subject = ConfigurationProperties.EmailSubject;
mailMessage.Body = ConfigurationProperties.EmailBody;
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = Encoding.UTF8;
mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
LogFile.Write(string.Format("Subject= {0}", mailMessage.Subject));
LogFile.Write(string.Format("Body= {0}", mailMessage.Body));
AddRecipients(mailMessage);
return mailMessage;
}
Is there any property I am missing in order to let outside emails recipients for receiving the emails?
There's no property that you can set to allow the mails to go outside of your network. This sounds like a configuration on your Exchange server and nothing to do with System.Net.Mail.
You'll need to talk with your system administrator.
For some reason my program does not send email using SMTP server, it stops somewhere in this code, and I can't debug it, because it happens with the compiled .exe
public static void sendLog(MailMessage mail) {
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(Constants.EMAIL_SENDER);
mail.To.Add(Constants.EMAIL_RECEIVER);
mail.Subject = Environment.UserName;
SmtpServer.Port = 587;
SmtpServer.Credentials = new NetworkCredential(Constants.EMAIL_SENDER, Constants.EMAIL_SENDER_PASSWORD);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
what I need is to know what try/catch to use, and to handle the proper Exception to write in a .txt file?
You should use proper SMTP Exception
catch (SmtpException ex)
{
// write to log file
string msg = "Failure sending email"+ex.Message+" "+ex.StackTrace;
}
When working locally it works fine, but when publishing the site, the mail function doesn't work. I suspect that the issue might lie with SmtpClient, but I am not sure. Does anyone know if there is a difference in how the network acts when running over the network vs locally?
My code:
public ActionResult SendMail(EmailModel model)
{
string host = ConfigurationManager.AppSettings.Get("SMTPHOST");
int port = Convert.ToInt16(ConfigurationManager.AppSettings.Get("SMTPPORT"));
string receiver = ConfigurationManager.AppSettings.Get("TOADDRESS");
string password = ConfigurationManager.AppSettings.Get("PASSWORD");
SmtpClient smtp = new SmtpClient(host, port);
smtp.Credentials = new NetworkCredential(receiver, password);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.EnableSsl = true;
MailMessage mailMsg = null;
var status = new HttpStatusCode();
try
{
if (ModelState.IsValid)
{
mailMsg = new MailMessage(model.from, receiver, model.subject, model.body);
smtp.Send(mailMsg);
return PartialView("_About");
}
else
{
status = HttpStatusCode.BadRequest;
}
}
catch (Exception ex)
{
status = HttpStatusCode.BadRequest;
SendInfoMail("address", "address", "Exception", ex.ToString());
}
return new HttpStatusCodeResult(status);
}
I think the code throws an exception, but since this only happens when the site is published, I can't debug it.
The below exception is thrown while trying to send mail by below code:
SMPT server requires a secure connection or the client was not authenticated. The server response was 5.5.1. Authentication required
C#
string E_mail_ID = "hidden";
try
{
SmtpClient gmail_client = new SmtpClient("smtp.gmail.com");
gmail_client.Port = 587;
gmail_client.EnableSsl = true;
gmail_client.Timeout = 100000;
gmail_client.DeliveryMethod = SmtpDeliveryMethod.Network;
gmail_client.UseDefaultCredentials = false;
gmail_client.Credentials = new NetworkCredential("hidden", "hidden");
MailMessage msg = new MailMessage();
msg.From = new MailAddress("hidden");
msg.To.Add(E_mail_ID.Trim());
msg.Body = "Request for quotation from Jeet fly ash products, a unit of Vidya shakti niyas";
msg.Attachments.Add(new Att![enter image description here][1]achment(pdfFile));
gmail_client.Send(msg);
MessageBox.Show("RFQ sent to vendor successfully");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Try the port: 465 - This is ssl for gmail.
Take a look: Configure Gmail-Account Outlook