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";
Related
I have been trying to use Cognito Sign In for my application at ASP.NET C# and I have managed to make the user sign up. However, when I am trying to implement the codes for Sign In there are 2 errors at these lines below :
CognitoUser user = new CognitoUser(username,ClientID,userPool,provider);
this line result in "CognitoUser does not contain a constructor that contain 4 arguments error"
and the 2nd error at this part :
authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
this line result in "CognitoUser does not contain definition for StartWithSrpAuthAsync and No Extension Method…accepting a first argument of type ” could be found" error
This is my full code :
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Amazon;
using Amazon.Runtime;
using Amazon.CognitoIdentity;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
using System.Threading.Tasks;
using System.Configuration;
using Amazon.Extensions.CognitoAuthentication;
namespace WebApplication2
{
public partial class WebForm5 : System.Web.UI.Page
{
const string PoolID = "poolid";
const string ClientID = "clientid";
static Amazon.RegionEndpoint Region = Amazon.RegionEndpoint.USEast1;
protected void Page_Load(object sender, EventArgs e)
{
string username = "user1";
string password = "pass";
string email = "email1";
SignInUser(username,password);
}
static async Task SignInUser(string username, string password)
{
AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Region);
CognitoUserPool userPool = new CognitoUserPool(PoolID, ClientID, provider);
CognitoUser user = new CognitoUser(username,ClientID,userPool,provider);
InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
{
Password = password
};
AuthFlowResponse authResponse = null;
try
{
authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
}
catch(Exception ex)
{
Console.WriteLine("Logon Failed: {0}\n", ex.Message);
return;
}
GetUserRequest getUserRequest = new GetUserRequest();
getUserRequest.AccessToken = authResponse.AuthenticationResult.AccessToken;
}
}
Any help will be appreciated.
Thank You
using System;
using System.Collections.Generic;
using System.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
// Add EAGetMail namespace
using EAGetMail;
namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
MailServer oServer = new MailServer("imap#gmail.com", "sample#gmail.com", "password", ServerProtocol.Imap4);
MailClient oClient = new MailClient("TryIt");
// Enable SSL connection
oServer.SSLConnection = true;
// Set 995 SSL POP3 port
oServer.Port = 995;
try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
// Receive email from POP3 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);
// Save email to local disk
oMail.SaveAs(fileName, true);
// Mark email as deleted from POP3 server.
oClient.Delete(info);
}
// Quit and pure emails marked as deleted from POP3 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Okay, so this is my code to retrieve emails. I wanted help regarding how I could authenticate the password I'll be passing as a parameter in:
MailServer oServer = new MailServer("imap#gmail.com", "sample#gmail.com", "password", ServerProtocol.Imap4).
Could someone help me out?
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.
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);
}
}