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);
Related
Everytime I try and update my SQL Db I am getting an error 'Process is terminated due to StackOverflowException' directly in the PM console. I think it's something being redundant and I believe it's related to an ApplicationDbContext<> statement but I have also referenced another students code and it seems to be identical. All Db sets are present as far as I can tell nothing has been changed with db names and the connection string looks correct.
my connection string in my config:
</connectionStrings>```
...and here is my seed method for roles (and my only one currently implemented)
protected override void Seed(ApplicationDbContext context)
{
if (!System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Launch();
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
if (!roleManager.RoleExists(RoleNames.ROLE_ADMINISTRATOR))
{
roleManager.Create(new IdentityRole(RoleNames.ROLE_ADMINISTRATOR));
}
if (!roleManager.RoleExists(RoleNames.ROLE_PROJECTMANAGER))
{
roleManager.Create(new IdentityRole(RoleNames.ROLE_PROJECTMANAGER));
}
if (!roleManager.RoleExists(RoleNames.ROLE_DEVELOPER))
{
roleManager.Create(new IdentityRole(RoleNames.ROLE_DEVELOPER));
}
if (!roleManager.RoleExists(RoleNames.ROLE_USER))
{
roleManager.Create(new IdentityRole(RoleNames.ROLE_USER));
}
ApplicationUser userA = userManager.FindByEmail("ashortnm88#gmail.com");
if (userA == null)
{
userA = new ApplicationUser()
{
UserName = "ashortnm88#gmail.com",
Email = "ashortnm88#gmail.com",
EmailConfirmed = true
};
IdentityResult userResult = userManager.Create(userA, "Abc&123!");
if (userResult.Succeeded)
{
var result = userManager.AddToRole(userA.Id, RoleNames.ROLE_ADMINISTRATOR);
}
}
ApplicationUser userB = userManager.FindByEmail("DemoPM#gmail.com");
if (userB == null)
{
userB = new ApplicationUser()
{
UserName = "DemoPM#gmail.com",
Email = "DemoPM#gmail.com",
EmailConfirmed = true
};
IdentityResult userResult = userManager.Create(userB, "Abc&123!");
if (userResult.Succeeded)
{
var result = userManager.AddToRole(userB.Id, RoleNames.ROLE_PROJECTMANAGER);
}
}
ApplicationUser userC = userManager.FindByEmail("DemoDev#gmail.com");
if (userC == null)
{
userC = new ApplicationUser()
{
UserName = "DemoDev#gmail.com",
Email = "DemoDev#gmail.com",
EmailConfirmed = true
};
IdentityResult userResult = userManager.Create(userC, "Abc&123!");
if (userResult.Succeeded)
{
var result = userManager.AddToRole(userC.Id, RoleNames.ROLE_DEVELOPER);
}
}
ApplicationUser userD = userManager.FindByEmail("DemoUser#gmail.com");
if (userD == null)
{
userD = new ApplicationUser()
{
UserName = "DemoUser#gmail.com",
Email = "DemoUser#gmail.com",
EmailConfirmed = true
};
IdentityResult userResult = userManager.Create(userD, "Abc&123!");
if (userResult.Succeeded)
{
var result = userManager.AddToRole(userD.Id, RoleNames.ROLE_USER);
}
}
//TICKET STASUES
context.TicketStatus.AddOrUpdate(
t => t.Name,
new TicketStatus { Name = "New" },
new TicketStatus { Name = "Open" },
new TicketStatus { Name = "Resolved" },
new TicketStatus { Name = "Archived" });
//TICKET TYPES
context.TicketTypes.AddOrUpdate(
t => t.Name,
new TicketType { Name = "A" },
new TicketType { Name = "B" },
new TicketType { Name = "C" },
new TicketType { Name = "D" });
//TICKET PRIORITY
context.TicketPriorities.AddOrUpdate(
t => t.Name,
new TicketPriority { Name = "High"},
new TicketPriority { Name = "Low" },
new TicketPriority { Name = "Medium" });
//TICKET
context.SaveChanges();
}
public class RoleNames
{
public const string ROLE_ADMINISTRATOR = "Administrator";
public const string ROLE_PROJECTMANAGER = "Project Manager";
public const string ROLE_DEVELOPER = "Developer";
public const string ROLE_USER = "Submittee";
}
}
I want to send some mails from my site.
I've created a template: OrderPlacedEmail.cshtml
#model OnlineCarStore.Models.PurchaseVM
<h1>Order Placed Email Notification</h1>
<p>#Model.Comments</p>
Dear #Model.Name,
<h2>Thank you.</h2>
<p>
You’ve made a purchase on #Model.Comments
</p>....and so on...
I've created a view model, and I use it like this:
var template = Server.MapPath("~/Templates/OrderPlaced.cshtml");
var viewModel = new PurchaseVM
{
GuId = new Guid(guidValue),
Name = name,
Address = address,
Phone = phone,
Email = email,
Comments = comments,
Date = DateTime.Now,
CartList = cartList
};
var body = Razor.Parse(template, viewModel);
As I understood, the Razor.Parse method, should replace all the details from my template with the values from view model. But, the body gets the value of the location of the template, as you can see below:
Can you please advise what I'm doing wrong.
If you wish there is a helper that i use
public static class HtmlOutputHelper
{
public static string RenderViewToString(ControllerContext context,
string viewPath,
object model = null,
bool partial = false)
{
// first find the ViewEngine for this view
ViewEngineResult viewEngineResult = null;
if (partial)
viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
else
viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
if (viewEngineResult == null)
throw new FileNotFoundException("View cannot be found.");
// get the view and attach the model to view data
var view = viewEngineResult.View;
context.Controller.ViewData.Model = model;
string result = null;
using (var sw = new StringWriter())
{
var ctx = new ViewContext(context, view,
context.Controller.ViewData,
context.Controller.TempData,
sw);
view.Render(ctx, sw);
result = sw.ToString();
}
return result;
}
}
On your controller
var viewModel = new PurchaseVM
{
GuId = new Guid(guidValue),
Name = name,
Address = address,
Phone = phone,
Email = email,
Comments = comments,
Date = DateTime.Now,
CartList = cartList
};
var emailTemplate = "~/Views/Templates/OrderPlaced.cshtml";
var emailOutput = HtmlOutputHelper.RenderViewToString(ControllerContext, emailTemplate, emailModel, false);
You also can use ActionMailerNext lib from NuGet Gallery for this scenario.
public class EmailController : MailerBase
{
//...
public EmailResult OrderPlaced(Order order)
{
MailAttributes.To.Add(new MailAddress("to#email.com"));
MailAttributes.From = new MailAddress("from#email.com");
return Email("OrderPlaced", new PurchaseVM
{
//...
});
}
//...
}
You can leave your View unchanged.
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);
}
I have a requirement where I need to update a user's google calendar when an event is inserted in the application's fullcalendar. I am using the peleyal's example for ASP.Net MVC and OAuth for Google API (using GoogleAuthorizationCodeFlow and AuthorizationCodeMvcApp) to handle this. I believe I have set up the credentials right in the google developer console as well.
I am able to create events on the google calendar locally without a problem. But from the azure deployed site I am not able to create the event. There are no exceptions/errors either. Is there anything that needs to be done from azure side to be able to create events and to use Google API?
var finalREsult = System.Threading.Tasks.Task.Run(async () =>
{
try
{
var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetaData()).AuthorizeAsync(cancellationToken);
if (result.Credential != null)
{
var service = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "****"
});
var startDate = patientappointment.DateScheduled.Value.ToUniversalTime();
var endDate = patientappointment.DateScheduled.Value.AddMinutes(patientappointment.AppointmentLengthMinutes).ToUniversalTime();
var myEvent = new Event
{
Summary = string.Format("{0}/{1}/{2} - {3}", patientappointment.CurrentUserName, patientappointment.LocationName, patientappointment.RoomName, patientappointment.Notes),
Location = "Ireland",
Start = new EventDateTime
{
DateTime = new DateTime(startDate.Year, startDate.Month, startDate.Day, startDate.Hour, startDate.Minute, 0),
TimeZone = "(GMT+01:00) Dublin"
},
End = new EventDateTime
{
DateTime = new DateTime(endDate.Year, endDate.Month, endDate.Day, endDate.Hour, endDate.Minute, 0),
TimeZone = "(GMT+01:00) Dublin"
},
Recurrence = new String[] { "RRULE:FREQ=WEEKLY;BYDAY=MO" }
// Attendees = new List<EventAttendee> { new EventAttendee { Email = "**0#gmail.com" } },
};
EventsResource.InsertRequest request = service.Events.Insert(myEvent, "******#group.calendar.google.com");
request.Execute();
}
}
catch (Exception ex)
{
throw ex;
}
Looking at the requests information, I dont see the request being sent to first autheticate and get the auth code from the deployed site.
internal class ForceOfflineGoogleAuthorizationCodeFlow : GoogleAuthorizationCodeFlow
{
public ForceOfflineGoogleAuthorizationCodeFlow
(AuthorizationCodeFlow.Initializer initializer)
: base((GoogleAuthorizationCodeFlow.Initializer)initializer) { }
public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest(string redirectUri)
{
return new GoogleAuthorizationCodeRequestUrl(new Uri(AuthorizationServerUrl))
{
ResponseType = "code",
ClientId = ClientSecrets.ClientId,
Scope = string.Join(" ", Scopes),
RedirectUri = redirectUri,
AccessType = "offline",
ApprovalPrompt = "force",
State = ""
};
}
};
public class AppFlowMetaData : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow = new ForceOfflineGoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = ConfigurationManager.AppSettings["ClientId"],
ClientSecret = ConfigurationManager.AppSettings["ClientSecret"]
},
Scopes = new[] { CalendarService.Scope.Calendar },
DataStore = null
});
public override string GetUserId(System.Web.Mvc.Controller controller)
{
return "user1";
}
public override IAuthorizationCodeFlow Flow
{
get { return flow; }
}
}
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);
}