How to Pass App Settings to Mail Method in C# - c#

I'm trying to pass the App Settings keys listed into the Send Email function so they can be customized by the user, but for some reason I can't get it to work. I've been testing with the "Body" key to see if I can even get 1 to work.
App Config File
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="MailHost" value="smtp.gmail.com" />
<add key="PortNumber" value="587" />
<add key="MailPassword" value="**********" />
<add key="Recipient" value="*************appspotmail.com" />
<add key="Body" value="Sent from WOX Mail Plugin." />
<add key="MailUser" value="**********#gmail.com" />
</appSettings>
</configuration>
Main.CS File
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wox.Plugin;
using System.Configuration;
using System.Net.Mail;
using System.Net;
namespace Wox.Plugin.Version1
{
public class Main :IPlugin
{
public void Init(PluginInitContext context)
{
}
public List<Result> Query(Wox.Plugin.Query query)
{
var subject = query.Search;
string emailbody = ConfigurationManager.AppSettings.Get("Body");
return new List<Result>()
{
new Result()
{
Title = string.Format("Add: {0}", subject),
IcoPath = "Images\\icon.png",
SubTitle = "Send New Task to Marvin",
Action = (Func<ActionContext, bool>) (c =>
{
Main.SendEmail(subject, emailbody);
return true;
})
}
};
}
public static void SendEmail(string inputsubject, string body)
{
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress("****************");
message.To.Add("********************8");
message.Subject = inputsubject;
message.Body = body;
message.IsBodyHtml = false;
using (SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.Credentials = (ICredentialsByHost)new NetworkCredential("*************", "************");
smtpClient.EnableSsl = true;
smtpClient.Send(message);
}
}
}
}
}
It feels like I've tried placing the ConfigurationManager line in every perceivable spot to make it happen, and nothing has worked. The subject goes through fine, but not the body.
The email always sends successfully, but the information in the body doesn't send. I've also tried appending it to the subject line, but it doesn't show up there either.

Related

C# SMTP Console App using free google smtp

I found the below snippet of code to send email.
It doesn't work for me.
It times out on send.
Any ideas, anyone?
It opens a blank window, then sits there and does nothing.
I get no mail.
Eventually it times out.
Sorry for being verbose. Stackexchange has weird filters that won't allow me to post question unless I added more text to the body. It complained there was too much code and not enough text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace TestHello
{
class Program
{
static void Main(string[] args)
{
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.Credentials = new NetworkCredential("klloil#gmail.com", "xxxxxxx");
smtpClient.EnableSsl = true;
MailMessage message = new MailMessage();
message.To.Add("kal#gmail.com");
message.Subject = "Password Manager Sync Account Created";
message.From = new MailAddress("xxxx#gmail.com");
message.Body = "My Email message";
smtpClient.Send(message);
}
}
}

Send e-mail in C# ASP.NET with parameters passed in from URL

I should mention this is just a learning project, and will never be hosted online. I am running the app locally.
I'm having two problems sending email with parameters passed in:
The main problem: it doesn't send.
The parameters don't populate the form in the view until after clicking send and redirecting to the same page, however they are displaying in the URL.
Here is my code:
Mail.cs (Model)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LotManager.Models
{
public class Mail
{
public string From = "myusername#gmail.com";
public string To { get; set; }
public string Subject = "Parking Alert";
public string Body { get; set; }
}
}
MailController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using LotManager.Controllers;
namespace LotManager.Controllers
{
public class MailController : Controller
{
//
// GET: /SendMailer/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ViewResult Index(LotManager.Models.Mail _objModelMail)
{
var to = Request.QueryString["To"];
ViewBag.To = to;
var body = Request.QueryString["Body"];
ViewBag.Body = body;
if (ModelState.IsValid)
{
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(_objModelMail.From);
string Body = body;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("mygmailusername", "mypassword"); //My actual account info goes here
smtp.EnableSsl = true;
try
{
smtp.Send(mail);
}
catch (Exception)
{
Console.WriteLine("The email was not sent, because I couldn't get it to work. Oops!");
}
return View("Index", _objModelMail);
}
else
{
return View();
}
}
}
}
Index.cshtml (Send Mail View)
#model LotManager.Models.Mail
#{
ViewBag.Title = "Send";
}
<h2>Send</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary()
<p>To: </p>
<p>#Html.TextBoxFor(m => m.To, new { #Value = #ViewBag.To })</p>
<p>Body: </p>
<p>#Html.TextBoxFor(m => m.Body, new { #Value = #ViewBag.Body })</p>
<input type="submit" value="Send" />
}
The code that passes the parameters to the URL:
#Html.Actionlink("Send Notification", "Index", "Mail", new { To = item.Employee.Email, Body = item.Description }, null)
A malicious user can use your page to spam people using your email account. That will quickly destroy your sender reputation with Gmail. It can be nearly impossible to recover from a badly tarnished sender reputation.
Issue 1
You're using the wrong SMTP port.
smtp.gmail.com requires port 465 for SSL or port 587 for TLS.
Issue 2
You are invoking the controller using a link (ActionLink), which creates a GET request. Your controller action will only be invoked for a POST however due to the [HttpPost] attribute. Either remove [HttpPost], or use a post action rather than a link to invoke the controller action.
The parameters are nor avialliable, becasue You are using [HttpPost]. Paramters are visible in GET not in POST.
About second problem look at Google documentation: https://support.google.com/a/answer/176600?hl=en
If you want to use port 25 you need to change server to smtp-relay.gmail.com. Otherwise change port to 465 for SSL or port 587 for TLS.

Send mail to multiple receipts from Database using Web service in asp .net c#

I have a sql server table in which im inserting Mail ID, subject,And Body of the mail.
And also i displayed the mail details in a gridview in another page. And there is checkbox for each row. Here I want to send these mails to corresponding Email IDs when user checked corresponding checkbox. The actuall problem is that i want to create a web service to send mail. Please help me to create a web service. I tried in some ways. My last Code for to create web service is given below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Mail;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MailService : System.Web.Services.WebService
{
public MailService()
{
//InitializeComponent();
}
[WebMethod]
public bool SendMail(string toAddress, string subject, string body)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("proc_MailData", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(ds);
try
{
MailMessage msg = new MailMessage();
msg.From = "john#averla.in";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string subjct = ds.Tables[0].Rows[i]["MSubject"].ToString();
string mail = ds.Tables[0].Rows[i]["MailID"].ToString();
string bdy = ds.Tables[0].Rows[i]["Body"].ToString();
msg.To = mail;
msg.Body = bdy;
msg.Subject = subjct;
}
SmtpMail.SmtpServer = "maildemo.averla.in";
SmtpMail.Send(msg);
return true;
}
catch (Exception exp)
{
return false;
}
}
}
1- add using statement
using System.Net.Mail;
2- to execute the smtp client
SmtpClient client = new SmtpClient();
client.Credentials=new NetworkCredential(username,password);
client.Send(message);
3- after you compile your web service and publish it, you should be able to navigate to the url and it will show you the operations like the image
then in your application, you can add the reference like i stated in the comments before
here some links that might help you
SmtpClient class
How to: Add a Reference to a Web Service
hope it will help you
regards

Error with changing SMTP Settings to use Config rather than setting it up in .cs

Currently my WPF application has the SMTP set up as followed:
string MailTo = txtBoxEmail.Text;
string MailFrom = "datfakeemaildoe#gmail.com ";
string Subject = "Cool Subject";
string Password = "*******";
SmtpClient smtpmail = new SmtpClient();
smtpmail.Host = "smtp.gmail.com";
smtpmail.Port = 587;
smtpmail.EnableSsl = true;
smtpmail.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpmail.UseDefaultCredentials = false;
smtpmail.Credentials = new NetworkCredential(MailFrom, Password);
MailMessage message = new MailMessage(MailFrom, MailTo, Subject, MessageTosend);
message.IsBodyHtml = true;
However, I'd like to manage all of this in the config rather than the .cs if possible.
Currently, I set up my App.Config as followed:
<configuration>
<appSettings>
<add key="host" value="smtp.gmail.com" />
<add key="port" value="587" />
<add key="MailFrom" value="datfakeemaildoe#gmail.com" />
<add key="Password" value="*******" />
</appSettings>
</configuration>
Problem is, how to I implement it properly now in the .cs
I tried this:
using System.Configuration;
using System.Net.Configuration;
using System.Net;
using System.Net.Mail;
...
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
...
string MessageTosend = #"there is html in here, trust me";
MailAddress Sender = new MailAddress(ConfigurationManager.AppSettings["MailFrom"]);
string MailTo = txtBoxEmail.Text;
string Subject = "Cool Subject";
SmtpClient smtp = new SmtpClient()
{
host = ConfigurationManager.AppSettings["host"],
port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]),
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network;
UseDefaultCredentials = false;
Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MailFrom"], ConfigurationManager.AppSettings["Password"])
};
MailMessage message = new MailMessage(ConfigurationManager.AppSettings["MailFrom, MailTo, Subject, MessageTosend);
message.IsBodyHtml = true;
...
BUT ConfigurationManager is generating an error that says does not exist in the current context, even though I have...
using System.Configuration;
using System.Net.Configuration;
using System.Net;
using System.Net.Mail;
...already. I just want to be able to change SMTP settings in the config rather than having to update the code behind for my application in case things change later.
Not sure if I'm doing it wrong or if I'm just missing something entirely. I referenced this to know how to use the app.config.
As stated on Scott Gu's blog, there's already a section in .config specifically for these settings, no need to do it in App Settings. The .NET framework automatically reads these settings in without the need to write C# to do it. Here's the MSDN documentation.
Example:
<system.net>
<mailSettings>
<smtp from="test#foo.com">
<network host="smtpserver1" port="25" userName="username" password="secret" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
No need to specify any code for loading of the configuration.
Figured out the ConfigurationManager problem.
While <system.net><mailSettings> ... works, so does my original <appSettings>. The reason why ConfigurationManager was running into a issue was because System.Configuration.dll was missing in my references (source)
Adding this, I was able to call the keys I added in my App.config
Then I changed the way it was used in the .cs
SmtpClient smtpmail = new SmtpClient();
smtpmail.Host = ConfigurationManager.AppSettings["host"];
smtpmail.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);
smtpmail.EnableSsl = true;
smtpmail.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpmail.UseDefaultCredentials = false;
smtpmail.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MailFrom"], ConfigurationManager.AppSettings["Password"]);
MailMessage message = new MailMessage(ConfigurationManager.AppSettings["MailFrom"], MailTo, Subject, MessageTosend);
message.IsBodyHtml = true;
Worked like a charm. :)

correct code for sending an email, asp.net

I have a form that allows a user to send an email to everyone on a mailing list (linq table). I'm having trouble with the correct code and syntax for linking to the smtp server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Web.Security;
using System.Web.Mail;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
public partial class MassEmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
mailingListClassDataContext Class = new mailingListClassDataContext();
var emaillist = from emails in Class.mailinglistMembers select emails.email;
foreach (var subcriber in emaillist)
{
MailMessage objMail = new MailMessage();
objMail.From = "test#test.com";
objMail.To = subcriber;
objMail.BodyFormat = MailFormat.Html ;
//The subject of the message
objMail.Subject = "test email that i hope works" ;
//he message text
objMail.Body = Editor1.Content;
//need help in this area
SmtpClient client = new SmtpClient();
SmtpClient.Send(objMail);
}
}
}
The best solution is to put the smtp server details in your web.config
<system.net>
<mailSettings>
<smtp>
<network
host="smtp.emailhost.com"
port="25"
userName="username"
password="password" />
</smtp>
</mailSettings>
</system.net>
<system.web>
using (var db = new mailingListClassDataContext())
{
var client = new System.Net.Mail.SmtpClient();
var recipients = from e in db.mailinglistMembers
select e.email;
foreach (string recipient in recipients)
{
var message = new System.Net.Mail.MailMessage("sender#example.com", recipient);
message.Subject = "Hello World!";
message.Body = "<h1>Foo bar</h1>";
message.IsBodyHtml = true;
client.Send(message);
}
}
Try setting up configuration in your web.config or machine.config. Make sure you've specified the correct address and port of the SMTP server.
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="network" from="me#example.com">
<network
host="localhost"
port="25"
defaultCredentials="true"
/>
</smtp>
</mailSettings>
</system.net>
</configuration>
You can pass the SMTP server IP or name in the constructor to SmtpClient or set it explicity through the Host property.
You probably want to set the Host (and possibly the Credentials) property on the SmptClient. The server (host) defaults to localhost.
Also consider creating the client instance outside of the loop.

Categories