testing smtp code without being blocked as spams - c#

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>.

Related

how do i use MailMessage with MFA or send emails with MFA enabled?

I am making an app with ASP.Net and I am using Sytem.Net.Mail.MailMessage function to send emails when a new entry is added to the database, but my business is using MFA on its accounts. I was wondering, whether there is any way to circumvent MFA; without the need to disable it in the first place.
Example code
MailAddress to = new MailAddress("email2#domain.com");
MailAddress from = new MailAddress("email1#domain.com");
MailMessage message = new MailMessage(from, to);
message.Subject = "New item added";
message.Body = "A new item has been added to the databse and is waiting approval.";
SmtpClient client = new SmtpClient("outlook.office365.com", 587)
{
Credentials = new NetworkCredential("email1#domain.com", "Password"),
EnableSsl = true
};
// code in brackets above needed if authentication required
try
{
client.Send(message);
}
catch (SmtpException ex)
{
Console.WriteLine(ex.ToString());
}

how to setup multiple SMTP email servers primary & backup in C#

I am trying to develop a email client. which sends email to the given recipients
using System.Net;
using System.Net.Mail;
MailMessage msg;
SmtpClient client;
SMTPURL=abc.xyz
SMTPPort=87
client = new SmtpClient(SMTPURL, SMTPPort);
client.Credentials = new NetworkCredential(senderID, senderPWD);
msg = new MailMessage();
msg.To.Add("rx#gmail.com");
msg.Body="hello hi bye";
client.Send(msg);
this code is working well, but I have a backup email server with URL 123.xyz
if my abc.xyz is down or I have wrong url I will get a SMTPException
Now my question is how to reroute my message to 123.xyz backup mail server
My assumption is to catch the SMTPException and change the SMTPURL to 123.xyz and resend, but is this a good way or any other alternates exists to reroute to secondary mail server ?
Thanks in advance
you should be able to use your basic try/catch block:
public void function sendemail()
{
try{
SendEmailByServer(primaryserverurl);
}
catch(SMTPException se)
{
sendemailbyserver(backupurl);
}
catch(Exception ex)
{
//something else broke
}
}
public void function SendEmailByServer(string server)
{
MailMessage msg;
SmtpClient client;
SMTPURL=server;
SMTPPort=87;
client = new SmtpClient(SMTPURL, SMTPPort);
client.Credentials = new NetworkCredential(senderID, senderPWD);
msg = new MailMessage();
msg.To.Add("rx#gmail.com");
msg.Body="hello hi bye";
client.Send(msg);
}

SmtpClient to Hosted Exchange Server gives - An attempt was made to access a socket in a way forbidden by its access permissions xxx.xxx.xxx.xxx:25

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;

Unable to read data from the transport connection?

This is my first post on Stack, and I've literally just started programming, so please, be patient.
I'm attempting to send an email to "x" email address when Button 1 is pressed. I've looked around, and every thread is jargon-heavy and not in my context. Please pardon me if this is a "newb' question, or if it's already thouroughly answered somewhere else.
The error I'm getting is "
Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed."
Here's my code
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 465;
smtp.Credentials = new NetworkCredential("myemail", "mypassword");
string to = "toemail";
string from = "myemail";
MailMessage mail = new MailMessage(from, to);
mail.Subject = "test test 123";
mail.Body = "test test 123";
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
Any help is greatly appreciated!
The error you're getting could come from a plethora of things from a failed connection, to the server rejecting your attempts, to the port being blocked.
I am by no means an expert on SMTP and its workings, however, it would appear you are missing setting some of the properties of the SmtpClient.
I also found that using port 465 is a bit antiquated, and when I ran the code using port 587, it executed without an issue. Try changing your code to something similar to this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net;
namespace EmailTest
{
class Program
{
static void Main(string[] args)
{
SendMail();
}
public static void SendMail()
{
MailAddress ma_from = new MailAddress("senderEmail#email", "Name");
MailAddress ma_to = new MailAddress("targetEmail#email", "Name");
string s_password = "accountPassword";
string s_subject = "Test";
string s_body = "This is a Test";
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
//change the port to prt 587. This seems to be the standard for Google smtp transmissions.
Port = 587,
//enable SSL to be true, otherwise it will get kicked back by the Google server.
EnableSsl = true,
//The following properties need set as well
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(ma_from.Address, s_password)
};
using (MailMessage mail = new MailMessage(ma_from, ma_to)
{
Subject = s_subject,
Body = s_body
})
try
{
Console.WriteLine("Sending Mail");
smtp.Send(mail);
Console.WriteLine("Mail Sent");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
Console.ReadLine();
}
}
}
}
Tested to work as well. Also of note: if your Gmail account does not allow "Less Secure" apps to access it, you'll get an error and message sent to your inbox stating an unauthorized access attempt was caught.
To change those settings, go here.
Hope this helps, let me know how it works out.

C# sending email code suddenly stopped working

i have the following code that has worked fine for months but suddently stopped working on this line:
smtpClient.Send(msg);
this is an internal application sending emails to internal people in my company
with the following error:
Mailbox unavailable. The server response was: 5.7.1 Unable to relay for ABC#comp.com
can anyone think of a reason why this code would work fine for ages and suddently just stop work ?
MailMessage msg = new MailMessage();
msg.From = new MailAddress(fromEmailAddress_);
msg.IsBodyHtml = true;
msg.To.Add(new MailAddress(email.Trim()));
msg.Subject = subject_;
msg.Body = body_;
msg.IsBodyHtml = true;
msg.Priority = MailPriority.High;
var smtpClient = new SmtpClient(_mailServer);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential(_user, _pwd);
try
{
smtpClient.Send(msg);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
The mail server you're connecting to has been tightened up to not allow relaying either for your credentials or from your network/IP. This is not a code issue (short of changing the SMTP server) but an issue or question for whoever manages the SMTP server you're using.
Apart from checking to ensure the smtp service is running you can try the following:
Try setting the SmtpDeliveryMethod enum to PickupDirectoryFromIis.
http://msdn.microsoft.com/en-us/library/system.net.mail.smtpdeliverymethod.aspx

Categories