C# code for sending email in mvc4 doubts - c#

am am doing a website in mvc4 using c#. currently i test this in localhost. I want to send passwords to registering persons email. i use the following code.
//model
public void SendPasswordToMail(string newpwd,string email)
{
string mailcontent ="Your password is "+ newpwd;
string toemail = email.Trim();
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("paru.mr#gmail.com");
mail.To.Add(toemail);
mail.Subject = "Your New Password";
mail.Body = mailcontent;
//Attachment attachment = new Attachment(filename);
//mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password"); //is that NetworkCredential
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception e)
{
throw e;
}
}
//controller
string newpwd;
[HttpPost]
public ActionResult SendPassword(int Id,string email)
{
bool IsMember=CheckMember(Id);
if (IsMember == true)
{
newpwd = new Member().RandomPaswordGen();
}
.......//here i want to call that model
return View();
}
Is the model is right or not. and what should be the return type of this model(now it is void and i dont know how this call in controller). and how to get default NetworkCredential. Please help me

Network Credential is the user name and password of the email sender (as in case of company a defualt mail address like noreply#abccompany.com).
Hence use you gmail user name and password in that case.
And you could use following code to send email.
var client = new SmtpClient()
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
};
var from = new MailAddress(Email);
var to = new MailAddress(Email);
var message = new MailMessage(from, to) { Body = Message, IsBodyHtml = IsBodyHtml };
message.Body += Environment.NewLine + Footer;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = Subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
var nc = new NetworkCredential("me#gmail.com", "password");
client.Credentials = nc;
//send email
client.Send(message);

Related

Unable to send the attachment to specified Email Id in ASP.NET,MVC

Here is my code in controller.My code works fine by send the subject and body,but I am unable to send the attachment?
Please help me thanks
namespace WebApplication1.Controllers
{
public class MailController : Controller
{
[HttpPost]
public ActionResult SendMail(MailModel obj,HttpPostedFileBase objFile)
{
string from = "vijaycsemvgr#gmail.com";
MailMessage mailmessage = new MailMessage();
mailmessage.To.Add(obj.ToMail);
mailmessage.From = new MailAddress(from);
mailmessage.Subject = obj.SubjectMail;
string body = obj.BodyMail;
mailmessage.Body = body;
if (objFile != null)
{
// string fileName = Path.GetFileName(objFile.FileName);
// var path = Path.Combine(Server.MapPath("/App_Data/uploads"));
mailmessage.Attachments.Add(new Attachment("E:\\6_25_Download\\Resume_Vijay"));
}
mailmessage.IsBodyHtml=true;
SmtpClient smtp = new SmtpClient(); //For sending mails,we need an smtp server
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential(from, "Vijay#123");// Enter senders User name and password
smtp.EnableSsl = true;
smtp.Send(mailmessage);
ViewBag.Message = "Sent";
// ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Message has been sent successfully.');", true);
return View("SendMail", obj);
}
// GET: Mail
[HttpGet]
public ActionResult SendMail()
{
return View();
}
}
}

how to send an email in asp.net mvc4

i want to send an email using a asp.net mvc 4 application i am using this method
public void send_mail(ProcRec.Models.AccuseReception _objModelMail)
{
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 seders User name and password
smtp.EnableSsl = true;
smtp.Send(mail);
}
My model :
public class AccuseReception
{
public string From { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
controller :
if (ModelState.IsValid)
{
AccuseReception confermation_mail = new AccuseReception {
From="xxxxxxxxxxx#gmail.com",
To ="ssssssss#gmail.com",
Subject ="mail_de confermation",
Body = "votre demande est enregistrer ",
};
send_mail(my_mail);
}
i get no error but the mail is not sending and the ModelState is not valid
ModelState belongs to a model that is passed to corresponding view/controller.
I see that in your controller you create a new AccuseReception so i assume that you are not getting AccuseReception as a model in this controller action.
This is the reason your ModelState.IsValid returns false and no mails are sent.
Try something like:
public void SendMail(ProcRec.Models.AccuseReception _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 seders User name and password
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
Here's a vb.net example that should work for you. I can't see your model in the example. But that should be enough:
Dim smtpClient As New SmtpClient(_ServerHost, _ServerPort)
smtpClient.Credentials = New Net.NetworkCredential(_EmailAddress, _EmailPass, String.Empty)
smtpClient.EnableSsl = True
smtpClient.Timeout = 60000
Dim mailmsg as New MailMessage
mailmsg.Subject = i_Subject
mailmsg.From = New MailAddress(emailAddress, displayName)
mailmsg.To.Clear()
mailmsg.IsBodyHtml = True
mailmsg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
' Add email addresses
mailmsg.To.Add("someemail#gmail.com")
mailmsg.Body = SomeBodyHTML
If Not String.IsNullOrEmpty(mailmsg.Body.Trim) Then
' Send message
smtpClient.Send(mailmsg)
End If
BTW if you want to easily send more complex html as emails, you can use Postal. In Postal you build views that are sent as emails:
aboutcode.net/postal

SmtpClient cannot send email

I try two application, one in java and one in C#. The java application can send email successfully but the C# cannot. Here is the two apps :
1.Java
final String username = "myaccount#mydomain";
final String password = "mypassword";
String smtpHost = "smtp.mydomain";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(username));
message.setSubject("Test send email");
message.setText("Hi you!");
Transport.send(message);
2.C#
string username = "myaccount#mydomain";
string password = "mypassword";
string smtpHost = "smtp.mydomain";
SmtpClient mailClient = new SmtpClient(smtpHost, 465);
mailClient.Host = smtpHost;
mailClient.Credentials = new NetworkCredential(username, password);
mailClient.EnableSsl = true;
MailMessage message = new MailMessage(username, username, "test send email", "hi u");
mailClient.Send(message);
So, what is the mistake i made in C# application? Why it cannot send email?
EDIT:
I have read this question How can I send emails through SSL SMTP with the .NET Framework? and it works. The deprecated System.Web.Mail.SmtpMail works but System.Net.Mail.SmtpClient doesn't. Why ?
3.This C# code work fine :
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver","smtp.mydomain");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport","465");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing","2");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "myaccount#mydomain");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "mypassword");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
myMail.From = "myaccount#mydomain";
myMail.To = "myaccount#mydomain";
myMail.Subject = "new code";
myMail.BodyFormat = System.Web.Mail.MailFormat.Html;
myMail.Body = "new body";
System.Web.Mail.SmtpMail.SmtpServer = "smtp.mydomain:465";
System.Web.Mail.SmtpMail.Send(myMail);
The .NET System.Net.Mail.SmtpClient class cannot handle implicit SSL connection. Implicit SSL connections are sent over Port 465, as the client is configured in your example.
You can use a third party library like AIM (Aegis Implicit Mail) to send implicit SSL messages.
You can try this code as well. Also sends the email in a seperate thread.
using System.Net.Mail;
public static void Email(string Content, string To, string Subject, List<string> Attach = null, string User = "sender#sender.com", string Password = "MyPassword", string Host = "mail.sender.com", ushort Port = 587, bool SSL = false)
{
var Task = new System.Threading.Tasks.Task(() =>
{
try
{
MailMessage Mail = new MailMessage();
Mail.From = new MailAddress(User);
Mail.To.Add(To);
Mail.Subject = Subject;
Mail.Body = Content;
if (null != Attach) Attach.ForEach(x => Mail.Attachments.Add(new System.Net.Mail.Attachment(x)));
SmtpClient Server = new SmtpClient(Host);
Server.Port = Port;
Server.Credentials = new System.Net.NetworkCredential(User, Password);
Server.EnableSsl = SSL;
Server.Send(Mail);
}
catch (Exception e)
{
MessageBox.Show("Email send failed.");
}
});
Task.Start();
}

send email in c#

i've tried to send email using this code..but an error occurred in smtp.Send(mail); messaging "Failure sending mail"
MailMessage mail = new MailMessage();
// set the addresses
mail.From = new MailAddress("from#gmail.com");
mail.To.Add(new MailAddress("to#yahoo.com"));
// set the content
mail.Subject = "test sample";
mail.Body = #"thank you";
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Credentials = new NetworkCredential("from#gmail.com", "password");
smtp.Send(mail);
In your code specify port number:
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587)
Also check out this thread Sending email through Gmail SMTP server with C#
You need to set smtp.EnableSsl = true for gmail.
Take a look at this class, it should work for you:
public class Email
{
NetworkCredential credentials;
MailAddress sender;
public Email(NetworkCredential credentials, MailAddress sender)
{
this.credentials = credentials;
this.sender = sender;
}
public bool EnableSsl
{
get { return _EnableSsl; }
set { _EnableSsl = value; }
}
bool _EnableSsl = true;
public string Host
{
get { return _Host; }
set { _Host = value; }
}
string _Host = "smtp.gmail.com";
public int Port
{
get { return _Port; }
set { _Port = value; }
}
int _Port = 587;
public void Send(MailAddress recipient, string subject, string body, Action<MailMessage> action, params FileInfo[] attachments)
{
SmtpClient smtpClient = new SmtpClient();
// setup up the host, increase the timeout to 5 minutes
smtpClient.Host = Host;
smtpClient.Port = Port;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = credentials;
smtpClient.Timeout = (60 * 5 * 1000);
smtpClient.EnableSsl = EnableSsl;
using (var message = new MailMessage(sender, recipient)
{
Subject = subject,
Body = body
})
{
foreach (var file in attachments)
if (file.Exists)
message.Attachments.Add(new Attachment(file.FullName));
if(null != action)
action(message);
smtpClient.Send(message);
}
}
}
fill
mail.Host
and
mail.Port
Properties with proper values
You should be using the using statement when creating a new MailMessage, plus a few things you missed out like port number and enableSSL
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("from#gmail.com");
mail.To.Add(new MailAddress("to#yahoo.com"));
mail.Subject = "test sample";
mail.Body = #"thank you";
SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
smtpServer.Port = 587;
smtpServer.Credentials = new NetworkCredential("from#gmail.com", "password");
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
}
Here's a basic GMAIL smtp email implementation I wrote a while ago:
public static bool SendGmail(string subject, string content, string[] recipients, string from)
{
bool success = recipients != null && recipients.Length > 0;
if (success)
{
SmtpClient gmailClient = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential("******", "*****") //you need to add some valid gmail account credentials to authenticate with gmails SMTP server.
};
using (MailMessage gMessage = new MailMessage(from, recipients[0], subject, content))
{
for (int i = 1; i < recipients.Length; i++)
gMessage.To.Add(recipients[i]);
try
{
gmailClient.Send(gMessage);
success = true;
}
catch (Exception) { success = false; }
}
}
return success;
}
It should work fine for you, but you'll need to add a valid gmail acocunt where I've marked in the code.
This is the function which i checked to send mail...and it's working properly.
`
private static bool testsendemail(MailMessage message)
{
try
{
MailMessage message1 = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg = string.Empty;
MailAddress fromAddress = new MailAddress("FromMail#Test.com");
message1.From = fromAddress;
message1.To.Add("ToMail#Test1.com");
message1.Subject = "This is Test mail";
message1.IsBodyHtml = true;
message1.Body ="You can write your body here"+message;
smtpClient.Host = "smtp.mail.yahoo.com"; // We use yahoo as our smtp client
smtpClient.Port = 587;
smtpClient.EnableSsl = false;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("SenderMail#yahoo.com", "YourPassword");
smtpClient.Send(message1);
}
catch
{
return false;
}
return true;
}`
Thank You.
Following is the C# code for Gmail Service
using System;
using System.Net;
using System.Net.Mail;
namespace EmailApp
{
internal class Program
{
public static void Main(string[] args)
{
String SendMailFrom = "Sender Email";
String SendMailTo = "Reciever Email";
String SendMailSubject = "Email Subject";
String SendMailBody = "Email Body";
try
{
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com",587);
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage email = new MailMessage();
// START
email.From = new MailAddress(SendMailFrom);
email.To.Add(SendMailTo);
email.CC.Add(SendMailFrom);
email.Subject = SendMailSubject;
email.Body = SendMailBody;
//END
SmtpServer.Timeout = 5000;
SmtpServer.EnableSsl = true;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new NetworkCredential(SendMailFrom, "Google App Password");
SmtpServer.Send(email);
Console.WriteLine("Email Successfully Sent");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
}
}
For reference: https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html

failed to send email from yahoo server in gmail is working

for sending email i set server name smtp.mail.yahoo.com and port is 465 i trying to send email but failed to send email
what is the correct servername and smtp port to send email using yahoo
what other configuration i needed to set ?
my code is here :
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(address);
message.Subject = subject;
message.From = new System.Net.Mail.MailAddress(from);
message.Body = body;
message.Bcc.Add(bcc);
message.CC.Add(cc);
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.mail.yahoo.com");
smtp.Credentials = new System.Net.NetworkCredential(emailid,password);
smtp.Port = 465;
smtp.EnableSsl = true;
smtp.Send(message);
I just tried the code and I think the yahoo mail server does not use SSL, because if you comment out
//smtp.Port = 465;
//smtp.EnableSsl = true;
it works.
I am not confirm about your smtp server settings these are working fine for me..
replace your smtp server settings and have idea from this code snippet.
some of the smtp server standart settings are here:
http://www.emailaddressmanager.com/tips/mail-settings.html
//Send mail using Yahoo id
protected void Button2_Click(object sender, EventArgs e)
{
String frmyahoo = "fromid#yahoo.com"; //Replace your yahoo mail id
String frmpwd = "fromidpwd"; //Replace your yahoo mail pwd
String toId = txtTo.Text;
String ccId = txtCc.Text;
String bccId = txtBcc.Text;
String msgsubject = txtSubject.Text;
String mailContent = txtContent.Text;
try
{
MailMessage msg = new MailMessage();
msg.To.Add(toId);
MailAddress frmAdd = new MailAddress(frmyahoo);
msg.From = frmAdd;
//Check user enter CC address or not
if (ccId != "")
{
msg.CC.Add(ccId);
}
//Check user enter BCC address or not
if (bccId != "")
{
msg.Bcc.Add(bccId);
}
msg.Subject = msgsubject;
//Check for attachment is there
if (FileUpload1.HasFile)
{
msg.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
msg.IsBodyHtml = true;
msg.Body = mailContent;
SmtpClient mailClient = new SmtpClient("smtp.mail.yahoo.com", 25);
NetworkCredential NetCrd = new NetworkCredential(frmyahoo, frmpwd);
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = NetCrd;
mailClient.EnableSsl = false;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.Send(msg);
clear();
Label1.Text = "Mail Sent Successfully";
}
catch (Exception ex)
{
Label1.Text = "Unable to send Mail Please try again later";
}
}

Categories

Resources