How can I send email using Gmail SMTP in asp.net mvc application? - asp.net-mvc-4

I want to send one mail to user whenever he/she register at my website.
I have created my gmail account for that, I've tried many samples from net but i'm not able to sent email yet.
Please help me in this regard.
Thanks,
vicky

I found a very good article on a website https://askgif.com about using Gmail SMTP with C#, so am sharing with you : https://askgif.com/blog/122/seding-email-using-gmail-smtp-in-asp-net-mvc-application/
Create Gmail Class comprises of all needed data type and member function as below
public class GMailer
{
public static string GmailUsername { get; set; }
public static string GmailPassword { get; set; }
public static string GmailHost { get; set; }
public static int GmailPort { get; set; }
public static bool GmailSSL { get; set; }
public string ToEmail { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public bool IsHtml { get; set; }
static GMailer()
{
GmailHost = "smtp.gmail.com";
GmailPort = 25; // Gmail can use ports 25, 465 & 587; but must be 25 for medium trust environment.
GmailSSL = true;
}
public void Send()
{
SmtpClient smtp = new SmtpClient();
smtp.Host = GmailHost;
smtp.Port = GmailPort;
smtp.EnableSsl = GmailSSL;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(GmailUsername, GmailPassword);
using (var message = new MailMessage(GmailUsername, ToEmail))
{
message.Subject = Subject;
message.Body = Body;
message.IsBodyHtml = IsHtml;
smtp.Send(message);
}
}
}
Then just used the following code wherever you want to send the email to the required email account.
GMailer.GmailUsername = "youremailid#gmail.com";
GMailer.GmailPassword = "YourPassword";
GMailer mailer = new GMailer();
mailer.ToEmail = "sumitchourasia91#gmail.com";
mailer.Subject = "Verify your email id";
mailer.Body = "Thanks for Registering your account.<br> please verify your email id by clicking the link <br> <a href='youraccount.com/verifycode=12323232'>verify</a>";
mailer.IsHtml = true;
mailer.Send();
Hope this will help you.
Mark as answer if this helps you.

Here is a Email class that can be used with ASP.NET MVC4 leveraging dependency injection. A full running sample application & unit tests that use this class can be found here in my github space https://github.com/fredo007/i6technology/tree/master/InsuranceSales.
I've also put together an article explaining methodology & use here http://prestoasp.net/how-to-send-email-using-gmail-smtp-in-an-asp-net-mvc-application/
public class GmailEmailService : IEmailService
{
private readonly SmtpConfiguration _config;
private const string GmailUserNameKey = "GmailUserName";
private const string GmailPasswordKey = "GmailPassword";
private const string GmailHostKey = "GmailHost";
private const string GmailPortKey = "GmailPort";
private const string GmailSslKey = "GmailSsl";
public GmailEmailService()
{
_config = new SmtpConfiguration();
var gmailUserName = ConfigurationManager.AppSettings[GmailUserNameKey];
var gmailPassword = ConfigurationManager.AppSettings[GmailPasswordKey];
var gmailHost = ConfigurationManager.AppSettings[GmailHostKey];
var gmailPort = Int32.Parse(ConfigurationManager.AppSettings[GmailPortKey]);
var gmailSsl = Boolean.Parse(ConfigurationManager.AppSettings[GmailSslKey]);
_config.Username = gmailUserName;
_config.Password = gmailPassword;
_config.Host = gmailHost;
_config.Port = gmailPort;
_config.Ssl = gmailSsl;
}
public bool SendEmailMessage(EmailMessage message)
{
var success = false;
try
{
var smtp = new SmtpClient
{
Host = _config.Host,
Port = _config.Port,
EnableSsl = _config.Ssl,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(_config.Username, _config.Password)
};
using (var smtpMessage = new MailMessage(_config.Username, message.ToEmail))
{
smtpMessage.Subject = message.Subject;
smtpMessage.Body = message.Body;
smtpMessage.IsBodyHtml = message.IsHtml;
smtp.Send(smtpMessage);
}
success = true;
}
catch (Exception ex)
{
//todo: add logging integration
//throw;
}
return success;
}
}

In addition to fredo Answer to clear web.config section
public GmailEmailService()
{
_config = new SmtpConfiguration();
var gmailUserName = ConfigurationManager.AppSettings[GmailUserNameKey];
var gmailPassword = ConfigurationManager.AppSettings[GmailPasswordKey];
var gmailHost = ConfigurationManager.AppSettings[GmailHostKey];
var gmailPort = Int32.Parse(ConfigurationManager.AppSettings[GmailPortKey]);
var gmailSsl = Boolean.Parse(ConfigurationManager.AppSettings[GmailSslKey]);
_config.Username = gmailUserName;
_config.Password = gmailPassword;
_config.Host = gmailHost;
_config.Port = gmailPort;
_config.Ssl = gmailSsl;
}
Now add in web.config file
<configuration>
<appSettings>
<add key="GmailUserNameKey" value="sender#gmail.com"/>
<add key="GmailPasswordKey" value="senderPassword"/>
<add key="GmailHostKey" value="smtp.gmail.com"/>
<add key="GmailPortKey" value="25"/>
<add key="GmailSslKey" value="true"/>
</appSettings>

Here is my solution for it, first time posting an answer. Happy coding
[HttpPost]
[ValidateAntiForgeryToken]
public async Task < ActionResult > Contact(EmailFormModel model) {
if (ModelState.IsValid) {
var body = "<p>Email From: {0} ({1})Message:</p><p>{2}</p>";
var message = new MailMessage();
//message.To.Add(new MailAddress("recipient#gmail.com")); // replace with valid value
message.To.Add(new MailAddress("haha")); // replace with valid value
//message.From = new MailAddress("sender#outlook.com"); // replace with valid value
message.From = new MailAddress("hahaha"); // replace with valid value,you cannot commend it, since it's required
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
message.IsBodyHtml = true;
using(var smtp = new SmtpClient()) {
var credential = new NetworkCredential {
UserName = "emailAddress", // replace with valid value
Password = "yourPassword" // Password = "password" // replace with valid value
};
//smtp.Credentials = credential;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("your emailAddress", "Password"); //You will be receive email from this email address
//smtp.Host = "smtp-mail.outlook.com";
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
return RedirectToAction("Sent");
}
}
return View(model);
}

Related

Passing list of object to Web API using RestSharp Client

I'm trying to send list of objects from MVC to WEBAPI using below methods. API is able to able receive the list from controller but, value of each item in the list is either empty/null on API side.
Can anyone please help me to fix this?
Controller Method:
private List<FCM.Models.Facility> GetFacilityDetails()
{
var url = "http://localhost:64664/";
var facilies = new List<Facility>();
facilies.Add( new Facility{ FCLT_ID = 100, FCLT_NM = "Facility 100" });
facilies.Add( new Facility{ FCLT_ID = 200, FCLT_NM = "Facility 200" });
facilies.Add( new Facility{ FCLT_ID = 300, FCLT_NM = "Facility 300" });
var json = JsonConvert.SerializeObject(facilies);
var _client = new RestClient(url);
var request = new RestRequest("api/facility/details", Method.GET) { RequestFormat = DataFormat.Json };
facilies.ForEach(fclt =>
request.AddParameter("facilites", fclt, ParameterType.GetOrPost));
var response = _client.Execute<List<FCM.Models.Facility>>(request);
if (response.Data == null)
{
throw new Exception(response.ErrorMessage);
}
return response.Data;
}
WebAPI method:
[Route("api/facility/details")]
public IEnumerable<Facility> GetFullAddress([FromUri] IEnumerable<Facility> facilities)
{
return null;
}
Like the comment suggested you maybe want to issue a POST request instead, but if you would like to send an array with a GETrequest you could do it like this (with System.Net.Http.HttpClient):
Add a Format method to you Facility class:
public class Facility
{
public int FCLT_ID { get; set; }
public string FCLT_NM { get; set; }
public string Format(int index)
{
return $"[{index}].FCLT_ID={FCLT_ID}&[{index}].FCLT_NM={FCLT_NM}";
}
}
Define a class which can format the array values:
public class FacilityList : List<Facility>
{
public string Format()
{
var builder = new StringBuilder();
for (var i = 0; i < Count; i++)
{
builder.Append(this[i].Format(i));
if(i != Count -1)
{
builder.Append("&");
}
}
return builder.ToString();
}
}
And then issue the request:
var client = new HttpClient()
{
BaseAddress = new Uri("http://localhost:64664/"),
DefaultRequestHeaders = {Accept = {new MediaTypeWithQualityHeaderValue("application/json")}}
};
var facilities = new FacilityList
{
new Facility {FCLT_ID = 100, FCLT_NM = "Facility 100"},
new Facility {FCLT_ID = 200, FCLT_NM = "Facility 200"},
new Facility {FCLT_ID = 300, FCLT_NM = "Facility 300"}
};
var format = facilities.Format();
var response = client.GetAsync("api/facility/details?" + format).GetAwaiter().GetResult();
var result = JsonConvert.DeserializeObject<IEnumerable<Facility>>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
This will bind to your controller action:
[Route("api/facility/details")]
public IHttpActionResult Get([FromUri] IEnumerable<Facility> facilities)
{
// Do stuff..
return Ok(facilities);
}

windows phone 7 app for Salesforce

I want to develop windows phone 7 app for doing crud(Create, Retrieve, Update, Delete) operations from salesforce. I'm successfully done an sample app in windows 8 and 8.1 using developerforce toolkit. But for windows phone 7 i'm not getting even toolkit also. Please any one help me for moving forward in developing windows phone 7 app. Thanks in advance.
Using
developerforce/Force.com-Toolkit-for-NET
You can try the libraries immmediately by installing the following DeveloperForce NuGet packages.
Install-Package DeveloperForce.Force
Install-Package DeveloperForce.Chatter
Username-Password Authentication Flow:-
Simply provide your consumer key, consumer secret, username, and password.
var auth = new AuthenticationClient();
await auth.UsernamePasswordAsync("YOURCONSUMERKEY", "YOURCONSUMERSECRET", "YOURUSERNAME", "YOURPASSWORD");
Web-Server Authentication Flow:-
var url =
Common.FormatAuthUrl(
"https://login.salesforce.com/services/oauth2/authorize", // if using sandbox org then replace login with test
ResponseTypes.Code,
"YOURCONSUMERKEY",
HttpUtility.UrlEncode("YOURCALLBACKURL"));
await auth.WebServerAsync("YOURCONSUMERKEY", "YOURCONSUMERSECRET", "YOURCALLBACKURL", code);
Creating the ForceClient or BulkForceClient:-
var instanceUrl = auth.InstanceUrl;
var accessToken = auth.AccessToken;
var apiVersion = auth.ApiVersion;
var client = new ForceClient(instanceUrl, accessToken, apiVersion);
var bulkClient = new BulkForceClient(instanceUrl, accessToken, apiVersion);
Example:-
var instanceUrl = auth.InstanceUrl;
var accessToken = auth.AccessToken;
var apiVersion = auth.ApiVersion;
var client = new ForceClient(instanceUrl, accessToken, apiVersion);
var bulkClient = new BulkForceClient(instanceUrl, accessToken, apiVersion);
```
### Sample Code
Below you'll find a few examples that show how to use the toolkit.
#### Create
You can create with the following code:
```
public class Account
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
...
var account = new Account() { Name = "New Account", Description = "New Account Description" };
var id = await client.CreateAsync("Account", account);
```
You can also create with a non-strongly typed object:
```
var client = new ForceClient(_consumerKey, _consumerSecret, _username, _password);
var account = new { Name = "New Name", Description = "New Description" };
var id = await client.CreateAsync("Account", account);
```
#### Update
You can update an object:
```
var account = new Account() { Name = "New Name", Description = "New Description" };
var id = await client.CreateAsync("Account", account);
account.Name = "New Name 2";
var success = await client.UpdateAsync("Account", id, account);
```
#### Delete
You can delete an object:
```
var account = new Account() { Name = "New Name", Description = "New Description" };
var id = await client.Create("Account", account);
var success = await client.DeleteAsync("Account", id)
```
#### Query
You can query for objects:
```
public class Account
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
...
var accounts = await client.QueryAsync<Account>("SELECT id, name, description FROM Account");
foreach (var account in accounts.records)
{
Console.WriteLine(account.Name);
}
```
### Bulk Sample Code
Below are some simple examples that show how to use the ```BulkForceClient```
**NOTE:** The following features are currently not supported
* CSV data type requests / responses
* Zipped attachment uploads
* Serial bulk jobs
* Query type bulk jobs
#### Create
You can create multiple records at once with the Bulk client:
```
public class Account
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
...
var accountsBatch1 = new SObjectList<Account>
{
new Account {Name = "TestStAccount1"},
new Account {Name = "TestStAccount2"}
};
var accountsBatch2 = new SObjectList<Account>
{
new Account {Name = "TestStAccount3"},
new Account {Name = "TestStAccount4"}
};
var accountsBatch3 = new SObjectList<Account>
{
new Account {Name = "TestStAccount5"},
new Account {Name = "TestStAccount6"}
};
var accountsBatchList = new List<SObjectList<Account>>
{
accountsBatch1,
accountsBatch2,
accountsBatch3
};
var results = await bulkClient.RunJobAndPollAsync("Account",
Bulk.OperationType.Insert, accountsBatchList);
```
The above code will create 6 accounts in 3 batches. Each batch can hold upto 10,000 records and you can use multiple batches for Insert and all of the operations below.
For more details on the Salesforce Bulk API, see [the documentation](https://resources.docs.salesforce.com/196/latest/en-us/sfdc/pdf/api_asynch.pdf "Salesforce Bulk API Docs").
You can also create objects dynamically using the inbuilt SObject class:
```
var accountsBatch1 = new SObjectList<SObject>
{
new SObject
{
{"Name" = "TestDyAccount1"}
},
new SObject
{
{"Name" = "TestDyAccount2"}
}
};
var accountsBatchList = new List<SObjectList<SObject>>
{
accountsBatch1
};
var results = await bulkClient.RunJobAndPollAsync("Account",
Bulk.OperationType.Insert, accountsBatchList);
```
#### Update
Updating multiple records follows the same pattern as above, just change the ```Bulk.OperationType``` to ```Bulk.OperationType.Update```
```
var accountsBatch1 = new SObjectList<SObject>
{
new SObject
{
{"Id" = "YOUR_RECORD_ID"},
{"Name" = "TestDyAccount1Renamed"}
},
new SObject
{
{"Id" = "YOUR_RECORD_ID"},
{"Name" = "TestDyAccount2Renamed"}
}
};
var accountsBatchList = new List<SObjectList<SObject>>
{
accountsBatch1
};
var results = await bulkClient.RunJobAndPollAsync("Account",
Bulk.OperationType.Update, accountsBatchList);
```
#### Delete
As above, you can delete multiple records with ```Bulk.OperationType.Delete```
```
var accountsBatch1 = new SObjectList<SObject>
{
new SObject
{
{"Id" = "YOUR_RECORD_ID"}
},
new SObject
{
{"Id" = "YOUR_RECORD_ID"}
}
};
var accountsBatchList = new List<SObjectList<SObject>>
{
accountsBatch1
};
var results = await bulkClient.RunJobAndPollAsync("Account",
Bulk.OperationType.Delete, accountsBatchList);

How to send 1 million of push notification (APNS) within few second using PushSharp as webservice?

to do that i made a web service to send push (by referencing PushSharp library). I request web service through my web application. i retrieve list of device token from database(using web application) send to web service using for loop to send push. and get result/exception for each one. This process is very slow and take long long time to send notification. If anybody suggest me to what should i do i will be grateful to you.
public ActionResult SendNowToken(int certificateInfoId, string message, string certificate, int badgeNo, int pushtype, string password, string countryJsonString)
{
if (IsPushParameterValid(certificateInfoId, message, certificate, badgeNo, pushtype, password, countryJsonString))
{
var countryObject = new JavaScriptSerializer().Deserialize<Country>(countryJsonString);
var errorList = new List<ErrorList>();
byte[] certificatePath = System.IO.File.ReadAllBytes(HttpContext.Server.MapPath("~/Content/certificate/" + certificate));
foreach (var aDeviceToken in countryObject.DeviceTokens)
{
try
{
var serviceClient = new PushServiceSoapClient();
string serviceResult = serviceClient.SendPushNotification(message, badgeNo, pushtype, aDeviceToken.Token, certificatePath, password);
if (serviceResult != "Sent Notification")
{
var delimiters = new[] { ' ' };
string[] errorResult = serviceResult.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string errorMessage = ConvertErrorCodeToErrorMessage(errorResult[0]);
var error = new ErrorList
{
CountryName = countryObject.CountryName,
ErrorTime = DateTime.Now,
ErrorMessage = errorMessage,
Token = aDeviceToken.Token
};
errorList.Add(error);
}
}
catch (Exception ex)
{
var error = new ErrorList
{
CountryName = countryObject.CountryName,
ErrorTime = DateTime.Now,
ErrorMessage = ex.Message,
Token = aDeviceToken.Token
};
errorList.Add(error);
}
}
if (errorList.Count != 0)
{
ViewBag.Message = "Push Notification does not send to country... ";
return PartialView("_SendAllError", errorList.ToList());
}
errorList.Clear();
}
return View();
}

Object reference not set to an instance of an object , youtube API

class Program
{
static void Main(string[] args)
{
string Appname;
string developerKey;
string username;
string password;
Appname = "a";
developerKey = "b";
username = "c";
password = "d";
YouTubeRequestSettings settings = new
YouTubeRequestSettings(Appname, developerKey, username, password);
YouTubeRequest request = new YouTubeRequest(settings);
Uri videoEntryUrl = new
Uri("http://www.youtube.com/watch?v=dOShGP0FM1U");
Video video = request.Retrieve<Video>(videoEntryUrl);
Comment MyComment = new Comment();
MyComment.Content = "random tango";
if (video != null)
{
request.AddComment(video, MyComment);
}
else
{
Console.Write("Video was null for some reason!");
Console.ReadKey();
}
}
}
For some reason the video keeps returning null and i can't figure out , i have tried everything i really need help with this project.

Create Registrant using GoToWebinar

I want to create a registrant for a webinar using GoToWebinar API's. I came across the code at gotowebinar api php
I provided my username and password to get the oAuth object. This worked perfectly fine as described.
Now I want to do something like this:
I have a Registration page. When user fills in the required details, selects the 'register to webinar' option and clicks on 'Submit', I want to enrol him for that webinar using CreateRegistrant API. The problem is, I am not able to get the oAuth object without providing username and password. Is there a way to pass this programatically and create oAuth object?
I store my API key, UserID and password in my WebConfig then read them into a Login Object for use when I do authorization. Here's how I do it in C#:
public class Login
{
public string UserId
{ get { return System.Configuration.ConfigurationManager.AppSettings["GTWUserId"]; } }
public string Password
{ get { return System.Configuration.ConfigurationManager.AppSettings["GTWPassword"]; } }
public string APIKey
{ get { return System.Configuration.ConfigurationManager.AppSettings["GTWAPIKey"]; } }
}
public string DoAuthorize()
{
Login lg = new Login();
string sError = "";
// first we need to create the uri for the web request
string uri = String.Format("https://api.citrixonline.com/oauth/access_token?grant_type=password&user_id={0}&password={1}&client_id={2}",
lg.UserId, lg.Password, lg.APIKey);
// then the request to login is created and sent. From the response
// we need to store at least the access token and the organizer key
// to use for further calls
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Accept = "application/json";
request.ContentType = "application/json";
try
{
var response = request.GetResponse();
//the following lines duplicate the response stream so we can read it for
//deserialization and also re-read it and write it out.
using (MemoryStream ms = new MemoryStream())
{
var stream = response.GetResponseStream();
stream.CopyTo(ms);
ms.Position = 0;
stream.Close();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ResponseDirectLogin));
var deserialized = (ResponseDirectLogin)ser.ReadObject(ms);
auth.OauthToken = deserialized.AccessToken;
auth.OrganizerKey = deserialized.OrganizerKey;
}
}
catch (WebException e)
{
using (var sr = new StreamReader(e.Response.GetResponseStream()))
sError = sr.ReadToEnd();
sError = String.Concat(sError, "/n", uri);
}
return sError;
}
public class Auth {
public string OauthToken { get; set; }
public string OrganizerKey { get; set; }
}
public static Auth auth = new Auth(); // This is actually in a BaseControlelr inherited by our MVC Home Controller.
public string DoRegister(string WebinarKey)
{
// Here we authorize if we haven't alerady
if (auth.OauthToken == null)
{
sMessage = DoAuthorize();
}
// first we need to create the uri for the web request
// OrganizerKey is your authorization key for the webinar organizer
string uri = String.Format(#"https://api.citrixonline.com/G2W/rest/organizers/{0}/webinars/{1}/registrants",
OrganizerKey, WebinarKey);
//then create and serialize the registrant object
// This is for when you have questions on your webinar, you can omit them if you don't have any
List<questions> q = GetQuestionKeys(Key, OrganizerKey);
List<response> responses_ = new List<response>();
foreach (var question in q)
{
response res1 = new response();
res1.questionKey = question.questionKey;
// determine which question and set the response
if (question.question == "question")
{
res1.responseText = "response";
responses_.Add(res1);
}
}
var registrant = new Registrant
{
firstName = FirstName,
lastName = LastName,
email = EmailAddress,
responses = responses_.ToArray()
};
JavaScriptSerializer ser = new JavaScriptSerializer();
string json = ser.Serialize(registrant);
// then the request to create a registrant is created and sent
// N.B. we need to include the access token to the headers to access
// the user's account and data
try {
WebClient client = new WebClient();
client.Headers = new WebHeaderCollection();
client.Headers.Add("Accept", "application/vnd.citrix.g2wapi-v1.1+json");
client.Headers.Add("Content-type", "application/json");
client.Headers.Add("Authorization", string.Format("OAuth oauth_token={0}", OAuthToken));
try
{
string resp = client.UploadString(uri, "POST", json);
var ok = ser.Deserialize<ResponseCreateRegistrantOk>(resp);
}
catch (WebException e)
{
//if there is an error, e.g. the registrant exists already
// we need an alternative deserialization
Stream s = new MemoryStream();
using (Stream response = e.Response.GetResponseStream())
{
byte[] buffer = new byte[1024];
int byteCount;
do
{
byteCount = response.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, byteCount);
} while (byteCount > 0);
}
s.Seek(0, SeekOrigin.Begin);
string content = new StreamReader(s, Encoding.UTF8).ReadToEnd();
s.Seek(0, SeekOrigin.Begin);
using (var err = new StreamReader(s))
{
var sb = new StringBuilder("Registration Error\n");
if (content.IndexOf("int_err_code") > -1)
{
var dupe = ser.Deserialize<ResponseCreateRegistrantDuplicate>(err.ReadToEnd());
sb.AppendFormat(String.Format("Error Code: {0}<br />", dupe.ErrorCode));
sb.AppendFormat(String.Format("Message: {0}<br />", dupe.Message));
}
else
{
var dupe = ser.Deserialize<ResponseCreateRegistrantDuplicate>(err.ReadToEnd());
sb.AppendFormat(String.Format("Description: {0}<br />", dupe.Description));
//sb.AppendFormat(String.Format("Incident: {0}<br />", dupe.Incident));
//sb.AppendFormat(String.Format("Registrant key: {0}<br />", dupe.RegistrantKey));
sb.AppendFormat(String.Format("Join Url: {0}<br />", dupe.JoinUrl));
}
sMessage = sb.ToString();
}
}
} catch (Exception exc) {
exc.Data.Add("stringInfo", "inside");
return "";
}
return sMessage;
}