how to send mail from .net? - email

i wrote the method as below i got the error as The specified string is not in the form required for an e-mail address. pls help me
SendMail("xyz#gmail.com","hi","heloo");
public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
{
string smtphost ="smtp.gmail.com";
int smtpport = 100;
string smtpuser ="xyz";
string smtppwd = "xyz";
SmtpClient client = null;
string MessageBody = string.Empty;
try
{
message = new MailMessage();
message.From = new MailAddress(smtpuser);
message.To.Add(toMailAddress);
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = mailSubject;
message.Body = mailMessage.ToString();
message.IsBodyHtml = true;
client = new SmtpClient();
client.Host = smtphost;
client.Port = smtpport;
client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
client.Send(message);
}
catch (Exception ex)
{
string x = ex.Message;
}
return true;
}

Your "from" user must be in the form of a valid email address.
message.From = new MailAddress(smtpuser);
Also, you will need to use the MailAddress constructor for the .To property as well.

Try, with port as 25 and IsSSLEnabled as true since gmail server is SSL enabled

Make sure the toMailAddress, and smtpuser are valid email address.
Try, Using smtpport = 587; provided by Gmail for Outgoing Mails (SMTP).
Hope this will make it work fine. Please list out the errors you encounter.

This code will work. What i have done are
proper smtphost
proper smtpport - 587
Enable SSL
set UseDefaultCredentials to false before setting the credentials
set DeliveryMethod
public static bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
{
string smtphost = "smtp.gmail.com";
int smtpport = 587;
string smtpuser = "youremail#gmail.com";
string smtppwd = "password";
SmtpClient client = null;
string MessageBody = string.Empty;
try
{
var message = new MailMessage();
message.From = new MailAddress(smtpuser);
message.To.Add(toMailAddress);
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = mailSubject;
message.Body = mailMessage.ToString();
message.IsBodyHtml = true;
client = new SmtpClient();
client.Host = smtphost;
client.EnableSsl = true;
client.Port = smtpport;
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
client.Send(message);
}
catch (Exception ex)
{
string x = ex.InnerException.Message;
Console.WriteLine(x);
}
return true;
}

Related

Send smtp email using group email Id

In my dot-net core application, I am sending email using SMTP server, it was working fine when I was using simple gmail account with password like this;
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.Credentials = new NetworkCredential("client#gmail.com","password");
MailMessage mm = new MailMessage("client#gmail.com", "user#gmail.com", subject, message);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
But now, I've to send this same email using Group email that does not have any passowrd, so I changed my code like this;
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.Credentials = new NetworkCredential("info#client.com","");
MailMessage mm = new MailMessage("info#client.com", "user#gmail.com", subject, message);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
But I'm getting this error;
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.
Is there any way to resolve this issue or this is impossible to send email using Group Email?

Mandrill.Net Adding Multiple Attachments

I am trying to send an email via Mandrill.Net, and am getting stuck trying to add multiple attachments. I have got the following code that create the list of attachments as IEnumerable, but I am getting the error
Unable to cast object of type 'System.Collections.Generic.List`1[Mandrill.Models.Attachment]' to type 'System.Collections.Generic.IEnumerable`1[Mandrill.Models.EmailAttachment]'.
The code is below:
try
{
EmailService ems = new EmailService();
EmailMessage msg = new EmailMessage();
List<EmailAddress> ToAdd = new List<EmailAddress>();
EmailAddress MainTo = new EmailAddress();
MainTo.Email = qe.ToAddress;
MainTo.Type = "bcc";
ToAdd.Add(MainTo);
msg.FromEmail = qe.FromAddress;
msg.FromName = qe.FromName;
msg.AddHeader("Reply-To", qe.ReplyTo);
msg.To = ToAdd;
msg.Subject = qe.Subject;
msg.Html = qe.Body;
msg.TrackClicks = true;
msg.TrackOpens = true;
// Need to add in Email Attachments
List<EmailAttachment> lea = new QueuedEmailModels().GetEmailAttachmentsByQueuedEmailID(qe.QueuedEmailsID); // Gets List of Attachments in DB
List<Attachment> lma = new List<Attachment>();
foreach(BRPA.EmailAttachment ea in lea)
{
byte[] array = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath("~/UploadedFiles/" + ea.AttachmentID));
Attachment at = new Attachment
{
Content = Convert.ToBase64String(array),
Name = ea.AttachmentName,
Type = ""
};
lma.Add(at);
}
msg.Attachments = (IEnumerable<Mandrill.Models.EmailAttachment>)lma.AsEnumerable();
// End of Attachments
await ems.SendMailviaMandrill(msg);
qe.Status = "Sent";
qe.DateTimeSent = DateTime.Now.AddHours(2);
await ctx.SaveChangesAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Thanks
Paul
Oops - Found the answer.
I had a class for EmailAttachment that was overriding the Mandrill.Models.EmailAttachment.
Specified the full name and all is good.

Unable to send email even when telnet connection is working

I am trying to send an email through my organisation's email with the help of SMTP however, the email isnt sending. I have tried using TelNet to test the network connection and it is connected.
Here are my codes for the web services
public List<string> sendEmail(string fromAdress, string toAddress, string subject, string body)
{
List<string> message = new List<string>();
string msg = "";
try
{
System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(fromAdress);
System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(toAddress);
string[] values = toAddress.Split(',');
MailMessage mail = new MailMessage();
mail.From = from;
for (int i = 0; i < values.Length; i++)
{
mail.To.Add(values[i].Trim());
}
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "172.20.192.204";
mail.IsBodyHtml = true;
mail.Subject = subject;
mail.Body = body;
client.Send(mail);
message.Add("success");
}
catch (SmtpFailedRecipientException ex)
{
// ex.FailedRecipient and ex.GetBaseException() should give you enough info.
msg = ex.GetBaseException().ToString();
message.Add(ex.GetBaseException().ToString());
}
return message;
}
Try with telnet (this is wthout ssl and without authentication)
telnet <your mail server domain> 25
Server>> 220-hello ...
mail from: <hello#your-email.com>
Server>> 250 ok ...
rcpt to: <email#to.com>
Server>> 250 ok ...
DATA
Server>> 354 Go ahead
Some text message
.
Server>> 250 Queued as dfgdfgdfg
quit
Server>> 221 Good bye.
Example wit authentication: http://namarginesie.blox.pl/2007/03/HOW-TO-telnet-do-serwera-SMTP.html

Autodiscover cannot process the given e-mail address. Only mailboxes and contacts are allowed

While sending email using ExchangeService is throwing Exception as Message is: "The Autodiscover service returned an error." and "Autodiscover cannot process the given e-mail address.
Only mailboxes and contacts are allowed".
public void SendEmail(string to, string cc, string subject, string body, string emailType)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.Credentials = new WebCredentials("test#outlook.com", "test");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("test#outlook.com", RedirectionUrlValidationCallback);
EmailMessage email = new EmailMessage(service);
email.ToRecipients.Add(to);
email.CcRecipients.Add(cc);
email.Subject = subject;
email.Body = new MessageBody(body);
email.Send();
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
if (redirectionUri.Scheme == "https")
{
result = true;
}
return true;
}
the above code is working fine with "...#microsoft.com" but not working with "...outlook.com"
can anyone help to resolve issue.

Sending Gmail through C# [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Sending Email in .NET Through Gmail
I have so many problems with sending mail through C#. I have tried forever on multiple apps and it never works....
Could someone PLEASE post some sample code that clearly labels where the sender and recipient go and offers help with the smtp sever dat or whatever!!
Something like this:
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("sender#gmail.com", "recipient#example.com", "subject", "body");
System.Net.Mail.SmtpClient emailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 465);
emailClient.Credentials = new System.Net.NetworkCredential("yourgmailusername", "yourpassword");
emailClient.Send(message);
Some code that I wrote some time ago for sending email through a webform:
//using System.Net.Mail;
MailMessage msg = new MailMessage();
msg.To.Add(RECIPIENT_ADDRESS); //note that you can add arbitrarily many recipient addresses
msg.From = new MailAddress(SENDER_ADDRESS, RECIPIENT_NAME, System.Text.Encoding.UTF8);
msg.Subject = SUBJECT
msg.SubjectEncoding = System.Text.Encoding.UTF8;
msg.Body = //SOME String
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.IsBodyHtml = false;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential(ADDRESS, PASSWORD);
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (SmtpException ex)
{
throw; //or handle here
}
I made this class to send via my gmail account when in my dev environment and use the SMTP in my Web.Config when in production. Essentially the same as noblethrasher with some deployment comfort.
There is a flag for "mailConfigTest"
/// <summary>
/// Send Mail to using gmail in test, SMTP in production
/// </summary>
public class MailGen
{
bool _isTest = false;
public MailGen()
{
_isTest = (WebConfigurationManager.AppSettings["mailConfigTest"] == "true");
}
public void SendMessage(string toAddy, string fromAddy, string subject, string body)
{
string gmailUser = WebConfigurationManager.AppSettings["gmailUser"];
string gmailPass = WebConfigurationManager.AppSettings["gmailPass"];
string gmailAddy = WebConfigurationManager.AppSettings["gmailAddy"];
NetworkCredential loginInfo = new NetworkCredential(gmailUser, gmailPass);
MailMessage msg = new MailMessage();
SmtpClient client = null;
if (_isTest) fromAddy = gmailAddy;
msg.From = new MailAddress(fromAddy);
msg.To.Add(new MailAddress(toAddy));
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = true;
if (_isTest)
{
client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
}
else
{
client = new SmtpClient(WebConfigurationManager.AppSettings["smtpServer"]);
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(msg);
}
}