On submit the contact form sends out an email to the specified email address in the web.config file. However at the moment it is posting the ID of the "Selected Services" - how do i get the value rendering instead of the ID? I've tried going through the list after appending the . to see what is available to me, i can't find value.
The values are already defined in Umbraco using a custom datatype.
Here is the surface controller;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml.XPath;
using Umbraco.Core.Services;
using Umbraco.Web.Mvc;
/// <summary>
/// Summary description for ContactSurfaceController
/// </summary>
namespace LiquidThinker2015
{
public class ContactSurfaceController : SurfaceController
{
public object XPathModeIterator { get; private set; }
public ActionResult ShowForm()
{
ContactModel myModel = new ContactModel();
List<SelectListItem> ListOfServices = new List<SelectListItem>();
XPathNodeIterator iterator = umbraco.library.GetPreValues(1435);
iterator.MoveNext();
XPathNodeIterator preValues = iterator.Current.SelectChildren("preValue", "");
while (preValues.MoveNext())
{
string preValue = preValues.Current.GetAttribute("id", "");
ListOfServices.Add(new SelectListItem
{
Text = preValues.Current.Value,
Value = preValues.Current.GetAttribute("id","")
});
myModel.ListOfServices = ListOfServices;
}
return PartialView("ContactForm", myModel);
}
public ActionResult HandleFormPost(ContactModel model)
{
var newComment = Services.ContentService.CreateContent(model.Name + " - " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"), CurrentPage.Id, "ContactFormula");
//DataTypeService myService = new DataTypeService();
//var SelectedService = myService.GetAllDataTypeDefinitions().First(x => x.Id == 1435);
//int SelectedServicePreValueId = myService.GetPreValuesCollectionByDataTypeId(SelectedService.Id).PreValuesAsDictionary.Where(x => x.Value.Value == model.SelectedService).Select(x => x.Value.Id).First();
newComment.SetValue("contactName", model.Name);
newComment.SetValue("companyName", model.Company);
newComment.SetValue("emailFrom", model.Email);
newComment.SetValue("telephoneNumber", model.Telephone);
newComment.SetValue("dropdownServices", model.SelectedService);
newComment.SetValue("contactMessage", model.Message);
Services.ContentService.SaveAndPublishWithStatus(newComment);
//Send out email
if (ModelState.IsValid)
{
var sb = new StringBuilder();
sb.AppendFormat("<p>Name: {0}</p>", model.Name);
sb.AppendFormat("<p>Company: {0}</p>", model.Company);
sb.AppendFormat("<p>Email: {0}</p>", model.Email);
sb.AppendFormat("<p>Phone: {0}</p>", model.Telephone);
sb.AppendFormat("<p>Service: {0}</p>", model.SelectedService); //THIS LINE HERE
sb.AppendFormat("<p>Message: {0}</p>", model.Message);
SmtpClient smtp = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress ma = new MailAddress(model.Email);
message.Subject = ConfigurationManager.AppSettings["ContactFormSubject"];
message.To.Add(new MailAddress(ConfigurationManager.AppSettings["ContactFormTo"]));
message.CC.Add(new MailAddress(ConfigurationManager.AppSettings["ContactFormCC"]));
message.From = ma;
message.Sender = new MailAddress(model.Email);
message.Body = sb.ToString();
message.IsBodyHtml = true;
try
{
smtp.Send(message);
}
catch (SmtpException smtpEx)
{
// Log or manage your error here, then...
return RedirectToUmbracoPage(1084); // Redirect to homepage.
}
return RedirectToUmbracoPage(1454);
}
return RedirectToUmbracoPage(1454);
}
}
}
Edit:
#co0ke when i do that i get this;
Or should i just try passing in "1435"?
You can use the method on the UmbracoHelper named .GetPreValueAsString(id) and pass in the id of the prevalue.
The UmbracoHelper is available as a property named 'Umbraco' on the PluginController which SurfaceController inherits from.
Related
I am using Rotativa to convert my view to pdf. I would like to send that generated pdf as an email attachment (without having to download it first to disk). I've been following a bunch of tutorials to do this but I just keep going round in circles. I would much appreciate any help I can get.
public async Task<IActionResult>SomeReport()
{
...
return new ViewAsPdf (report)
}
return view();
MemoryStream memoryStream = new MemoryStream();
MimeMessage msg = new MimeMessage();
MailboxAddress from = new MailboxAddress ("Name", "emailAddress")
msg.From.Add(from);
MailboxAddress to = new MailboxAddress ("Name", "emailAddress")
msg.From.Add(to);
BodyBuilder bd = new BodyBuilder();
bb.HtmlBody ="some text";
bb.Attachments.Add("attachmentName", new MemoryStream());
msg.Body = bb.ToMessageBody();
SmtpClient smtp = new SmtpClient();
smtp.Connect("smtp.gmail.com",465, true);
smtp.Authenticate("emailAddress", "Pwd");
smtp.Send(msg);
smtp.Disconnect(true);
smtp.Dispose();
Edit
Parent View from which Email is sent
#Model MyProject.Models.EntityViewModel
<a asp-action= "SendPdfMail" asp-controller ="Student" asp-route-id = "#Model.Student.StudentId">Email</a>
...
SendPdfMail action in Student Controller
public async Task<IActionResult> SendPdfMail(string id)
{
var student = await context.Student. Where(s => s.StudentId == id);
if (student != null)
{
...
var viewAsPdf = new ViewAsPdf("MyPdfView", new{route = id})
{
Model = new EntityViewModel(),
FileName = PdfFileName,
...
}
}
};
Complete answer using Rotativa.AspNetCore. Code is developed in VS 2019, Core 3.1, Rotativa.AspNetCore 1.1.1.
Nuget
Install-package Rotativa.AspNetCore
Sample controller
public class SendPdfController : ControllerBase
{
private const string PdfFileName = "test.pdf";
private readonly SmtpClient _smtpClient;
public SendPdfController(SmtpClient smtpClient)
{
_smtpClient = smtpClient;
}
[HttpGet("SendPdfMail")] // https://localhost:5001/SendPdfMail
public async Task<IActionResult> SendPdfMail()
{
using var mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress("a#b.c"));
mailMessage.From = new MailAddress("c#d.e");
mailMessage.Subject = "mail subject here";
var viewAsPdf = new ViewAsPdf("view name", <YOUR MODEL HERE>)
{
FileName = PdfFileName,
PageSize = Size.A4,
PageMargins = { Left = 1, Right = 1 }
};
var pdfBytes = await viewAsPdf.BuildFile(ControllerContext);
using var attachment = new Attachment(new MemoryStream(pdfBytes), PdfFileName);
mailMessage.Attachments.Add(attachment);
_smtpClient.Send(mailMessage); // _smtpClient will be disposed by container
return new OkResult();
}
}
Options class
public class SmtpOptions
{
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
In Startup#ConfigureServices
services.Configure<SmtpOptions>(Configuration.GetSection("Smtp"));
// SmtpClient is not thread-safe, hence transient
services.AddTransient(provider =>
{
var smtpOptions = provider.GetService<IOptions<SmtpOptions>>().Value;
return new SmtpClient(smtpOptions.Host, smtpOptions.Port)
{
// Credentials and EnableSsl here when required
};
});
appsettings.json
{
"Smtp": {
"Host": "SMTP HOST HERE",
"Port": PORT NUMBER HERE,
"Username": "USERNAME HERE",
"Password": "PASSWORD HERE"
}
}
There's not quite enough to go on, but you need something like this:
MimeMessage msg = new MimeMessage();
MailboxAddress from = new MailboxAddress ("Name", "emailAddress");
msg.From.Add(from);
MailboxAddress to = new MailboxAddress ("Name", "emailAddress");
msg.To.Add(to);
BodyBuilder bb = new BodyBuilder();
bb.HtmlBody ="some text";
using (var wc = new WebClient())
{
bb.Attachments.Add("attachmentName",wc.DownloadData("Url for your view goes here"));
}
msg.Body = bb.ToMessageBody();
using (var smtp = new SmtpClient())
{
smtp.Connect("smtp.gmail.com",465, true);
smtp.Authenticate("emailAddress", "Pwd");
smtp.Send(msg);
smtp.Disconnect(true);
}
Notice this adds the attachment before calling .ToMessageBody(), as well as fixing at least four basic typos.
But I doubt this will be enough... I suspect ViewAsPdf() needs more context than you get from a single DownloadData() request, and you'll need to go back to the drawing board to be able to provide that context, but this at least will help push you in the right direction.
I'm trying to write a program to read through an exchange mailbox. I'm very new to c#, so please excuse if the error is too obvious.
Here's the code and it fails when I try to bind the EmailMessage and gives me the error - "The name 'id' does no exist in the current context"
using Microsoft.Exchange.WebServices.Data;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResetOraclePassword
{
class Program
{
static void Main(string[] args)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new WebCredentials("abc#xyz.com", "xxxxxxx");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("abc#xyz.com", RedirectionUrlValidationCallback);
Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
PropertySet propSet = new PropertySet(EmailMessageSchema.InternetMessageHeaders, EmailMessageSchema.Body, EmailMessageSchema.HasAttachments, EmailMessageSchema.Attachments,
EmailMessageSchema.Subject, EmailMessageSchema.From, EmailMessageSchema.Sender, EmailMessageSchema.DisplayCc, EmailMessageSchema.DisplayTo, EmailMessageSchema.DateTimeReceived,
EmailMessageSchema.InternetMessageId);
propSet.RequestedBodyType = BodyType.Text;
EmailMessage abc = EmailMessage.Bind(service, id, propSet);
Console.WriteLine(abc.Subject);
Console.WriteLine(abc.InternetMessageId);
Console.WriteLine(abc.DateTimeReceived.ToString());
Console.WriteLine(abc.From.Name);
Console.WriteLine(abc.DisplayTo);
Console.WriteLine(abc.DisplayCc);
Console.WriteLine(abc.Body.Text);
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
}
}
the error should be in this line
EmailMessage abc = EmailMessage.Bind(service, id, propSet);
it said that idis not defined in your code, so you need to initialize id in your code. For example, if id is string then you can define like
string id = "any value";
I'm using asp.net c# mvc with Entity Framework to create a website. In there I want to create reset password part And I have the following code for the controller.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ResetPassword(ResetPasswordViewModel resetpasswordmodel)
{
if (ModelState.IsValid)
{
//User user;
MembershipUser member;
using (TheFoodyContext db = new TheFoodyContext())
{
var foundemail = (from e in db.Users
where e.email == resetpasswordmodel.Email
select e.email).FirstOrDefault();
if (foundemail != null)
{
member = Membership.GetUser(foundemail.ToString());
}
else
{
member = null;
}
}
if (member != null)
{
//Generate password token that will be used in the email link to authenticate user
var token = WebSecurity.GeneratePasswordResetToken(member.Email);
// Generate the html link sent via email
string resetLink = "<a href='"
+ Url.Action("ResetPassword", "Account", new { rt = token }, "http")
+ "'>Reset Password Link</a>";
// Email stuff
string subject = "Reset your password for TheFoody.com";
string body = "You link: " + resetLink;
string from = "abcd123#gmail.com";
string to = resetpasswordmodel.Email;
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to);
message.Subject = subject;
message.Body = body;
SmtpClient client = new SmtpClient();
// Attempt to send the email
try
{
client.Send(message);
}
catch (Exception e)
{
ModelState.AddModelError("", "Issue sending email: " + e.Message);
}
}
else // Email not found
{
ModelState.AddModelError("", "No user found by that email.");
}
}
return View(resetpasswordmodel);
}
Here var token = WebSecurity.GeneratePasswordResetToken(member.Email); code part which is used to generate password token that will be used in the email link to authenticate user has a error for WebSecurity part. It is saying
The name 'WebSecurity' does not exist in the current context.
I have added following also
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TheFoody.Models;
using TheFoody.DataAccess;
using System.Web.Security;
using System.Web.Mail;
using System.Net.Mail;
I don't know how to fix this error.
You need to add reference WebMatrix.WebData to your project ! WebSecurity Class
After that add using to your class.
using WebMatrix.WebData;
I have a program that I lost the source code to and cannot figure out what I am doing wrong now that we had an IP change. What I am trying to do is step through a table and have it send emails with the corresponding report. Any ideas what is going wrong? I don't get any errors but I also don't get any emails (and yes the SMTP server works).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Web;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace AutomatedReporting
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataClasses1DataContext dc = new DataClasses1DataContext();
foreach (var item in dc.reportsSent1s)
{
string matchedCaseNumber = item.CaseNumberKey;
(new MyReportRenderer()).RenderTest(matchedCaseNumber);
}
dc.ExecuteCommand("TRUNCATE TABLE reportsSent1");
}
public class MyReportRenderer
{
private rs2005.ReportingService2005 rs;
private rs2005Execution.ReportExecutionService rsExec;
public void RenderTest(String matchedCaseNumber)
{
string HistoryID = null;
string deviceInfo = null;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
rs2005Execution.Warning[] warnings = null;
string[] streamIDs = null;
rs = new rs2005.ReportingService2005();
rsExec = new rs2005Execution.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://***.***.***.***/ReportServer_DEVELOPMENT/ReportService2005.asmx";
rsExec.Url = "http://***.***.***.***/ReportServer_DEVELOPMENT/ReportExecution2005.asmx";
try
{
// Load the selected report.
rsExec.LoadReport("/LawDept/LawDeptTIC", HistoryID);
// Set the parameters for the report needed.
rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[1];
parameters[0] = new rs2005Execution.ParameterValue();
parameters[0].Name = "CaseNumberKey";
parameters[0].Value = matchedCaseNumber;
rsExec.SetExecutionParameters(parameters, "en-us");
// get pdf of report
Byte[] results = rsExec.Render("PDF", deviceInfo,
out extension, out encoding,
out mimeType, out warnings, out streamIDs);
//pass paramaters for email
DataClasses1DataContext db = new DataClasses1DataContext();
var matchedBRT = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.BRTNumber).SingleOrDefault();
var matchedAdd = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.Premises).SingleOrDefault();
var matchedDocument = (from c in db.GetTable<Document>()
where c.DocIDKey == SelectedRow.DocIDKey
select c).SingleOrDefault();
db.Documents.DeleteOnSubmit(matchedDocument);
db.SubmitChanges();
var matchedEmail = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.Email).SingleOrDefault();
//send email with attachment
MailMessage message = new MailMessage("Reports#acmetaxabstracts.com", matchedEmail, "Report for property located at " + matchedAdd, "Attached is the Tax Information Certificate for the above captioned property");
MailAddress copy = new MailAddress("acmetaxabstracts#gmail.com");
message.CC.Add(copy);
SmtpClient emailClient = new SmtpClient("***.***.***.***");
message.Attachments.Add(new Attachment(new MemoryStream(results), String.Format("{0}" + matchedBRT + ".pdf", "BRT")));
emailClient.Send(message);
//db.reportsSent1s.DeleteOnSubmit(matchedItem);
//db.SubmitChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
My problem is
"Affiche()" does not exist for the current context.
class OPPSVotesStatistiques
The code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Configuration;
namespace Components.Jobs
{
class OPPSVotesStatistiques : SPJobDefinition
{
private Pmail p;
public OPPSVotesStatistiques()
: base()
{
}
public OPPSVotesStatistiques(string jobName, SPWebApplication webApplication)
: base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
{
this.Title = "ListLogger";
}
public override void Execute(Guid contentDbId)
{
Pmail p = new Pmail();
InsretListAvis addAvis = new InsretListAvis();
List<AttributMail> listMail = Pmail.Affiche();
foreach (AttributMail m in listMail)
{
info = addAvis.Insert(m.Projet, m.Phase, m);
}}}
class Pmail
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Exchange.WebServices.Data;
using Microsoft.Exchange.WebServices.Autodiscover;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.Text.RegularExpressions;
namespace Components.MailVote
{
class Pmail
{
public Pmail()
{
}
public static List<AttributMail> Affiche()
{
List<AttributMail> lmail = new List<AttributMail>();
try
{
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
//service.Credentials = new NetworkCredential( "{Active Directory ID}", "{Password}", "{Domain Name}" );
service.Credentials = new WebCredentials("mail#site.com", "pass");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("mail#site.com", RedirectionUrlValidationCallback);
Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
//The search filter to get unread email
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
itempropertyset.RequestedBodyType = BodyType.Text;
ItemView view = new ItemView(50);
view.PropertySet = itempropertyset;
//Fire the query for the unread items
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
foreach (Item item in findResults.Items)
{
AttributMail m = new AttributMail();
item.Load(itempropertyset);
m.From = (item as EmailMessage).Sender.Name;
m.Sujet = item.Subject;
m.Txt = item.Body;
m.Date = item.DateTimeReceived.TimeOfDay.ToString();
m.Cc = item.DisplayCc;
lmail.Add(m);
} }
catch(Exception ex){
}
return lmail;}}}
it's a timer job to read mails and to insert data into SPlist .
Make Pmail.affiche() public.
So,
public class Pmail
{
public List<AttributMail> affiche()
{
...
}
}
Also, it is C# convention to name methods with uppercase, so Affiche()
EDIT:
Okay, now we have the information, the problem is it's static like I said in the comments!
The code you posted must work:
Pmail.Affiche();
Pmail p = new Pmail();
p.Affiche(); // will not work as you can't call a static method on an instance.
So
public override void Execute(Guid contentDbId)
{
InsretListAvis addAvis = new InsretListAvis();
List<AttributMail> listMail = Pmail.Affiche(); // static call
foreach (AttributMail m in listMail)
{
info = addAvis.Insert(m.Projet, m.Phase, m);
}
}