I am trying to send email from my controller (MVC4) through exchange server i.e. (outlook.office365.com as I can see it from my outlook settings) using SMTP but could not succeed. I tried solution from many previous posts but cant get any clue. I sincerely appreciate any help from you guys..
Here is my mail configuration:
<system.net>
<mailSettings>
<smtp>
<network host="smtp.office365.com" userName="no-reply#mydomain.com" password="defaultPassword"/>
</smtp>
</mailSettings>
</system.net>
Here is my class for email:
public class eMail
{
public eMail() { }
private string Sender{ get; set; }
private List<string> Recipients { get; set; }
private string Subject { get; set; }
private string Body { get; set; }
public bool SendEmail()
{
try
{
var smptClient = new SmtpClient { EnableSsl = true };
MailMessage newEmail = new MailMessage();
foreach (var reciepent in this.Recipients )
newEmail.To.Add(new MailAddress(recipient));
newEmail.From = new MailAddress(this.Sender);
newEmail.Subject = this.Subject;
newEmail.Body = this.Body;
newEmail.IsBodyHtml = false;
smptClient.Send(newEmail);
return true;
}
catch { return false; }
}
}
in above code if I use "EnableSsl = true", I get error "Server does not support secure connections.". Still if I disable ssl, I get following error:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
use this piece of code:
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("someone#somedomain.com", "SomeOne"));
msg.From = new MailAddress("you#yourdomain.com", "You");
msg.Subject = "This is a Test Mail";
msg.Body = "This is a test message using Exchange OnLine";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("your user name", "your password");
client.Port = 25; // give 587 if 25 is blocked
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
client.Send(msg);
lblText.Text = "Message Sent Succesfully";
}
catch (Exception ex)
{
lblText.Text = ex.ToString();
}
Finally I'd resolve the issue which was related to domain we have.
For the person who are facing similar problem, here is how I had fixed it. Follwoing were my email settings:
<network host="smtp.office365.com" userName="no-reply#mydomain.com" password="defaultPassword"/>
If you are on domain then your username must have domain mentioned in your username i.e. no-reply#domain.mydomain.com and bang :)
Cheers!!
Related
I have the following class to send emails.
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
if (message != null)
{
MailMessage mail = new MailMessage();
mail.To.Add(message.Destination);
mail.From = new MailAddress("test#test.com");
mail.Subject = message.Subject;
string Body = message.Body;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.test.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
//
smtp.Credentials = new System.Net.NetworkCredential("username", "pass");
smtp.EnableSsl = true;
return smtp.SendMailAsync(mail);
}
return Task.FromResult(0);
}
}
Our IT informed us that he open the port 587 on the firewall. However, the emails can't be sent.
In C:\inetpub\logs\LogFiles\W3SVC2 logs I have the following messages without getting an error.
2021-02-08 12:02:13 192.168.1.2 GET /signalr/connect transport=serverSentEvents&clientProtocol=1.5&connectionToken=1%2FM7LMZNVeWfN1mD1D9geTBdC7vVjo6nQRtD%2BrQv%2BVwUUdC6eE6jbKaIq2CUlrUsaylRVyJgz6fFqoQDsxJ9%2F77L8kizNCyZYkAs5nxK2T6Crz4xlKu9lAS1z9%2FHDen84sd7IVBASCnCm46jfQlrdg%3D%3D&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&tid=0 81 test#gmail.com 192.168.1.1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/88.0.4324.146+Safari/537.36 http://192.168.1.2:81/Account/ReSendEmailConfirmationTokenAsync?userID=51abfa03-6d09-40bb-8e4c-89117515ff&subject=Confirm%20your%20account 200 0 0 494899
Can you please help me?
Actually in my application i have a feedback form to get the complaints through email. So how can i achieve to get an email from each users to some particular email ("abed#gmail.com").
Usually, i use user account credentials to send email to others.
Code to send email
public ActionResult SendEmail(string SentTo, string Text)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("senderemail");
msg.To.Add(SentTo);
msg.Subject = "Password";
msg.Body = Text;
msg.Priority = MailPriority.High;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.UseDefaultCredentials = false;
//client.EnableSsl = false;
client.Credentials = new NetworkCredential("emailaddress", "password");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
bool result = false;
try
{
client.Send(msg);
}
catch (Exception)
{
result = false;
}
return View();
}
But how can i receive an email from contact form?
Looking for some help to get the solution for my issue. Any help appreciated. Thanks in advance !!!
I'm developing an ASP.Net MVC 3 web application. One of my Razor Views allows a user to upload a file (selected from their computer) and then this is attached to an outgoing email.
Below is my code to date, but unfortunately it does not work. By this I mean the email (and of course the attachment) never gets sent. Although, when I step threw/ debug my code locally no errors occur, and none as well on the live server.
Does anyone see what I'm missing? Any advice would be greatly appreciated.
Thanks.
Controller
[HttpPost]
public ActionResult CvUpload(HttpPostedFileBase file)
{
//Get logged in user
User user = _accountService.GetUser(_formsAuthService.GetLoggedInUserID());
if (file != null && file.ContentLength > 0)
{
_emailService.SendUpload(user, file);
return RedirectToAction("CvUpload", new { feedBack = "Success" });
}
return RedirectToAction("CvUpload", new { feedBack = "Failed" });
}
Email Service
public void SendUpload(User user, HttpPostedFileBase file)
{
string messageBody = "";
string subject = "Upload";
string[] toAddress = new string[1];
string ToBCC = "";
if (isProduction.Equals("true"))
{
toAddress[0] = "myemail#test.com";
sendEmail(toAddress, ToBCC, adminFromEmail, adminFromEmail, subject, messageBody, true, emailServer, file);
}
else
{
// DO NOT SEND EMAIL
}
}
private bool sendEmail(string[] toAddresses, string ToBCC, string fromAddress, string replyto, string subject, string body, bool ishtml, string emailHost, HttpPostedFileBase file)
{
bool mailSent = false;
try
{
MailMessage mail = new MailMessage();
foreach (string addresss in toAddresses)
mail.To.Add(addresss);
mail.From = new MailAddress(fromAddress);
mail.ReplyToList.Add(replyto);
mail.Bcc.Add(ToBCC);
mail.Subject = subject;
mail.Body = body;
if(file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
mail.Attachments.Add(new Attachment(file.InputStream, fileName));
}
if (ishtml)
mail.IsBodyHtml = true;
else
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = emailHost;
smtp.Send(mail);
mailSent = true;
}
catch (Exception)
{
mailSent = false;
}
return mailSent;
}
I have a similar service and this is what I have although the attachments are saved so they can be reused later.
var attachment = new Attachment(path);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(path);
disposition.ModificationDate = File.GetLastWriteTime(path);
disposition.ReadDate = File.GetLastAccessTime(path);
disposition.FileName = attachmentName.Name;
disposition.Size = new FileInfo(path).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
mailMessage.Attachments.Add(attachment);
I'm using MVC3 and need to send an email to a user. I don't want to use a gmail server. But, I do want to use server 10.1.70.100. I don't understand what I am doing wrong. Here is my code:
var fromAddress = new MailAddress("sum1#abc.com", "From Name"); var toAddress = new MailAddress(EmailID, "To Name");
const string fromPassword = "";//To be Filled
const string subject = "Verification Mail";
string body = "You have successfully registered yourself. Please Enter your Verification code " + code.ActivatedCode;
var smtp = new SmtpClient
{
Host = "10.1.70.100",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(),
Timeout = 100000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Can someone suggest a way through which I don't have to give my credentials??
I prefer doing this on the following way:
Web.config:
<system.net>
<mailSettings>
<smtp from="Description">
<network host="your.smtpserver" password="" userName="" />
</smtp>
</mailSettings>
</system.net>
Your code:
var smtpClient = new SmtpClient();
smtpClient.Send(mail);
For our OSS project we use this little helper. Hope it helps.
public void SendEmail(string address, string subject, string message)
{
string email = ConfigurationManager.AppSettings.Get("email");
string password = ConfigurationManager.AppSettings.Get("password");
string client = ConfigurationManager.AppSettings.Get("client");
string port = ConfigurationManager.AppSettings.Get("port");
NetworkCredential loginInfo = new NetworkCredential(email, password);
MailMessage msg = new MailMessage();
SmtpClient smtpClient = new SmtpClient(client, int.Parse(port));
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress(address));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}
Folks,
I wanted to send a few emails with different subject and body asynchronously. here is my code
Email.cs
public string To;
public string CC;
public string Subject;
public string Host;
public string Port;
public string Body;
public MailMessage mail;
public SmtpClient smtp;
public void send()
{
smtp = new SmtpClient();
mail = new MailMessage();
mail.To.Add(To);
if (this.CC !="" && this.CC !=null) mail.CC.Add(CC);
mail.CC.Add(CCIDBizzMail);
mail.Subject = this.Subject;
mail.From = new MailAddress(From);
mail.IsBodyHtml = true;
smtp.Host = this.SMTPAddress;
mail.Body = this.Body;
smtp.Credentials = new System.Net.NetworkCredential
(this.From, this.Password);
smtp.EnableSsl = false;
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
smtp.SendAsync(mail, null);
}
private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
String token = (string)e.UserState;
if (e.Cancelled)
{
}
if (e.Error != null)
{
}
else
{
mail.Dispose();
smtp.Dispose();
}
}
here is my code to send an email:
Email objEmail = new Email();
objEmail.Subject = "Thank You for Your Order!";
objEmail.Body = "first email";
objEmail.To: "ssss#mail.com"
objEmail.Send();
objEmail.Subject = "Thank You for Your Order!";
objEmail.Body = "second email";
objEmail.To: "tttt#mail.com"
objEmail.Send();
However, tttt#mail.com never received an email. my website always send to ssss#mail.com
can you help me to solve this issue?
Here you try to send an email with Asynchronous type with out making a new object Email.
I suggest to try two thinks.
Make new on every email send
{
Email objEmail = new Email();
objEmail.Subject = "Thank You for Your Order!";
objEmail.Body = "first email";
objEmail.To: "ssss#mail.com"
objEmail.Send();
}
{
Email objEmail = new Email();
objEmail.Subject = "Thank You for Your Order!";
objEmail.Body = "second email";
objEmail.To: "tttt#mail.com"
objEmail.Send();
}
Or change the Email routine to
public string To;
public string CC;
public string Subject;
public string Host;
public string Port;
public string Body;
public void send()
{
using(var smtp = new SmtpClient())
{
using(mail = new MailMessage())
{
mail.To.Add(To);
if (this.CC !="" && this.CC !=null) mail.CC.Add(CC);
mail.CC.Add(CCIDBizzMail);
mail.Subject = this.Subject;
mail.From = new MailAddress(From);
mail.IsBodyHtml = true;
smtp.Host = this.SMTPAddress;
mail.Body = this.Body;
smtp.Credentials = new System.Net.NetworkCredential
(this.From, this.Password);
smtp.EnableSsl = false;
// maybe here you place extra code for the errors
// http://msdn.microsoft.com/en-us/library/swas0fwc.aspx
smtp.Send(mail);
}
}
}
If the email is send using localhost and if you like to send many emails, is better to send them right way and not asynchronous.