I'm trying to read through a gmail account to get gps data that is being sent there ( in the text of a email) from an moble phone (my phone)
using (Pop3Client cl = new Pop3Client())
{
cl.UserName = "crash893";
cl.Password = "password";
cl.ServerName = "pop.gmail.com";
cl.AuthenticateMode = Pop3AuthenticateMode.Pop;
cl.Ssl = true;
cl.Authenticate();
///Get first mail of my mailbox
Pop3Message mg = cl.GetMessage(1); <<<<<<<<<< ERROR
String MyText = mg.BodyText;
///If the message have one attachment
Pop3Content ct = mg.Contents[0];
///you can save it to local disk
ct.DecodeData("c:\\test.txt");
}
but I get a exception on the "get first mail of mailbox message
"Higuchi.Net.Pop3.Pop3ConnectException: Pop3 connection is closed
at Higuchi.Net.Pop3.Pop3Client.SendCommand(String inCommand)
at Higuchi.Net.Pop3.Pop3Client.Execute(String inCommand, Boolean inIsMultiLine)
at Higuchi.Net.Pop3.Pop3Client.Execute(Pop3Command inCommand)
at Higuchi.Net.Pop3.Pop3Client.GetMessage(Int64 inMailIndex)"}
Ideally what i would like to do is open this read all the new unread emails in this account for a certain subject line then read the data in the body and mark them as read
does anyone know why its erroring out
does anyone have any experince with c#mail that hey could point me in the right direction for reading and makring emails as read etc
It is not possible to mark emails as read using the POP protocol.
Try using IMAP.
cl.Port = 995;
using (Pop3Client cl = new Pop3Client())
{
cl.UserName = "ewgsdssw";
cl.Password = "sdgwsegw";
cl.ServerName = "pop.gmail.com";
cl.AuthenticateMode = Pop3AuthenticateMode.Pop;
cl.Port = 995;
cl.Ssl = true;
cl.Authenticate();
///Get first mail of my mailbox
///
int total = Convert.ToInt16(cl.GetTotalMessageCount());
while (total >= 1)
{
Pop3Message mg = cl.GetMessage(total);
if (mg.Subject == "I am Here")
{
// http://maps.google.com/maps?q=38.89552,-77.43265
//(+/- 76 metres.)
string location = mg.BodyText;
location = location.Replace("http://maps.google.com/maps?q=","~");
location = location.Replace("metres.)\r\n\r\n","~");
location = location.Split('~')[1];
location = location.Replace("(+/- ", ",");
location = location.Replace("\r\n", "");
string[] data = location.Split(',');
string lat = data[0];
string lon = data[1];
string res = data[2];
DateTime time = mg.Date;
textBox1.AppendText(string.Format("Lat: {0} LON: {1} Res: {2} TIME: {3}\r\n",lat,lon,res,time.ToString()));
}
total--;
}
}
I do not have experience with C#Mail, and this answer may not help, but I've experienced weirdness in the past while trying to write email send/receive related code.
Turned out the antivirus software we were running at work had a whitelist of allowed .EXE's that could make in/outbound POP3 or SMTP connections. Any chance this is your problem?
Related
I'm a complete newbie to EWS, but am trying to convert a happily functioning IMAP program into EWS & am having problems accessing simple fields in the managed API, e.g. From, Sender, BodyType. Can anyone spot what I am doing wrong? Many thanks folks.
ItemView view = new ItemView(99);
SearchFilter.Exists filter = new SearchFilter.Exists(EmailMessageSchema.Id);
FindItemsResults<Item> inboxMessageList = service.FindItems(WellKnownFolderName.Inbox, view);
Console.WriteLine("Inbox message count: " + inboxMessageList.TotalCount);
int messageCounter = 1;
//message loop
foreach (Item thisMessage in inboxMessageList)
{
//Collect info about current email message
Item thisItem = Item.Bind(service, thisMessage.Id);
Console.WriteLine("Current message ID: " + thisMessage.Id);
string uniqueID = "EMAIL-" + DateTime.UtcNow.ToString("yyyyMMdd-HHmmss-fff");
string messageTo = thisItem.DisplayTo;
string messageCC = thisItem.DisplayCc;
string messageFrom = //cant get this to work
string messageSubject = thisItem.Subject;
string messageDate = thisMessage.DateTimeReceived.ToString();
int noOfAttachments = 0;
Boolean messageHasAttachments = thisMessage.HasAttachments;
if (messageHasAttachments) noOfAttachments = thisMessage.Attachments.Count();
string isBodyHtml = //cant seem to implement this either
Boolean domainblacklistResult = fn.CheckIfDomainBlacklisted(messageFrom);
Boolean emailblacklistResult = fn.CheckIfEmailBlacklisted(messageFrom);
To access information about the email message, you need to bind it as an EmailMessage, instead of as an Item. Example:
EmailMessage message = EmailMessage.Bind(service, thisMessage.Id);
I need to query the test equipment on a GPIB bus.
I tried looking through NationalInstruments.VisaNS.
NationalInstruments.NI4882.AddressCollection.GetEnumerator();
i.e. GPIB::6::INSTR, GPIB::7::INSTR, ......GPIB::20::INSTR.
If you are using Vb or C# use Visa32.bas or Visa32.cs from the sample programs disk
int DefaultSessionId= 0;
int SessionId= 0;
int LastStatus = 0;
string Address = "GPIB0::6" ; //any address
//Session Open
LastStatus = visa32.viOpenDefaultRM(out DefaultSessionId);
//Connection Open
LastStatus = visa32.viOpen(DefaultSessionId, Address + "::INSTR", 0, 0, out sessionId);
LastStatus = visa32.viSetAttribute(SessionId, visa32.VI_ATTR_TERMCHAR, 13);// Set the termination character to carriage return (i.e., 13);
LastStatus = visa32.viSetAttribute(SessionId, visa32.VI_ATTR_TERMCHAR_EN, 1);// Set the flag to terminate when receiving a termination character
LastStatus = visa32.viSetAttribute(SessionId, visa32.VI_ATTR_TMO_VALUE, 2000);// Set timeout in milliseconds; set the timeout for your requirements
//Communication
LastStatus = visa32.viPrintf(SessionId, command + "\n");//device specific commands to write
StringBuilder message = new StringBuilder(2048);
LastStatus = visa32.viScanf(SessionId, "%2048t", message);//Readback
//Session and Connection Close
visa32.viClose(SessionId);
visa32.viClose(DefaultSessionId);
Reference from
I would like to implement the Perforce command "Get Revision [Changelist Number]" using the Perforce .NET API (C#). I currently have code that will "Get Latest Revision", but I need to modify it to get a specific changelist.
To sync the data with a changelist number, what should I do?
Source
// --------Connenct----------------
Perforce.P4.Server server = new Perforce.P4.Server(
new Perforce.P4.ServerAddress("127.0.0.1:9999"));
Perforce.P4.Repository rep = new Perforce.P4.Repository(server);
Perforce.P4.Connection con = rep.Connection;
con.UserName = m_P4ID;
string password = m_P4PASS;
Perforce.P4.Options opconnect = new Perforce.P4.Options();
opconnect.Add("-p", password);
con.Connect(opconnect);
if (con.Credential == null)
con.Login(password);
//----------Download----------
string clientPath = #"C:\P4V\";
string ws_client = clientPath;
Perforce.P4.Client client = new Perforce.P4.Client();
client.Name = ws_client;
client.Initialize(con);
con.CommandTimeout = new TimeSpan(0);
IList<Perforce.P4.FileSpec> fileList = client.SyncFiles(new Perforce.P4.Options());
//----------Disconnect------------
con.Disconnect();
con.Dispose();
Edit: Attempt 1
Perforce.P4.DepotPath depot = new Perforce.P4.DepotPath("//P4V//");
Perforce.P4.LocalPath local = new Perforce.P4.LocalPath(ws_client);
Perforce.P4.FileSpec fs = new Perforce.P4.FileSpec(depot, null, local,
Perforce.P4.VersionSpec.Head);
IList<Perforce.P4.FileSpec> listFiles = new List<Perforce.P4.FileSpec>();
listFiles.Add(fs);
IList<Perforce.P4.FileSpec> foundFiles = rep.GetDepotFiles(listFiles,
new Perforce.P4.Options(1234)); // 1234 = Changelist number
client.SyncFiles(foundFiles, null);
Error Message
Usage: files/print [-o localFile -q] files...Invalid option: -c.
I do not know the problem of any argument.
Or there will not be related to this reference source?
Edit 2
I tried to solve this problem. However, it does not solve the problem yet.
Perforce.P4.Changelist changelist = rep.GetChangelist(1234);
IList<Perforce.P4.FileMetaData> fileMeta = changelist.Files;
In this case, I could get only the files in the changelist. I would like to synchronize all files of the client at the moment of changelist 1234.
SyncFiles takes an optional FileSpec arg. You can specify a file path and a revision specifier with that FileSpec arg. Here are the relevant docs:
FileSpec object docs
SyncFiles method docs
You don't need to run GetDepotFiles() to get the FileSpec object; you can just create one directly as shown in the FileSpec object docs. The error you are getting with GetDepotFiles() is because it expects the change number to be specified as part of the FileSpec object passed into as the first argument to GetDepotFiles().
To expand further, GetDepotFiles() calls the 'p4 files' command when it talks to Perforce. new Perforce.P4.Options(1234) generates an option of '-c 1234' which 'p4 files' doesn't accept. That's why the error message is 'Usage: files/print [-o localFile -q] files...Invalid option: -c.'
I struggled with the same problem as well. Finally based on Matt's answer I got it working. Please see simple example below.
using (Connection con = rep.Connection)
{
//setting up client object with viewmap
Client client = new Client();
client.Name = "p4apinet_solution_builder_sample_application_client";
client.OwnerName = "p4username";
client.Root = "c:\\clientRootPath";
client.Options = ClientOption.AllWrite;
client.LineEnd = LineEnd.Local;
client.SubmitOptions = new ClientSubmitOptions(false, SubmitType.RevertUnchanged);
client.ViewMap = new ViewMap();
client.ViewMap.Add("//depotpath/to/your/file.txt", "//" + client.Name + "/clientpath/to/your/file.txt", MapType.Include);
//connecting to p4 and creating client on p4 server
Options options = new Options();
options["Password"] = "p4password";
con.UserName = "p4username";
con.Client = new Client();
con.Connect(options);
con.Client = rep.CreateClient(client);
//syncing all files (in this case 1) defined in client's viewmap to the changelist level of 12345
Options syncFlags = new Options(SyncFilesCmdFlags.Force, 100);
VersionSpec changeListLevel = new ChangelistIdVersion(12345);
List<FileSpec> filesToBeSynced = con.Client.ViewMap.Select<MapEntry, FileSpec>(me => new FileSpec(me.Left, changeListLevel)).ToList();
IList<FileSpec> results = con.Client.SyncFiles(filesToBeSynced, syncFlags);
}
The following code should allow you to sync a depot to a particular revision (changelist number).
string uri = "...";
string user = "...";
string workspace = "...";
string pass = "...";
int id = 12345; // the actual changelist number
string depotPath = "//depot/foo/main/...";
int maxItemsToSync = 10000;
Server server = new Server(new ServerAddress(uri));
Repository rep = new Repository(server);
server = new Server(new ServerAddress(uri));
rep = new Repository(server);
Connection con = rep.Connection;
con.UserName = user;
con.Client = new Client();
con.Client.Name = workspace;
// connect
bool connected = con.Connect(null);
if (connected)
{
try
{
// attempt a login
Perforce.P4.Credential cred = con.Login(pass);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
con.Disconnect();
connected = false;
}
if (connected)
{
// get p4 info and show successful connection
ServerMetaData info = rep.GetServerMetaData(null);
Console.WriteLine("CONNECTED TO " + info.Address.Uri);
Console.WriteLine("");
try
{
Options opts = new Options();
// uncomment below lines to only get a preview of the sync w/o updating the workspace
//SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.Preview, maxItemsToSync);
SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.None, maxItemsToSync);
VersionSpec version = new ChangelistIdVersion(id);
PathSpec path = new DepotPath(depotPath);
FileSpec depotFile = new FileSpec(path, version);
IList<FileSpec> syncedFiles = rep.Connection.Client.SyncFiles(syncOpts, depotFile);
//foreach (var file in syncedFiles)
//{
// Console.WriteLine(file.ToString());
//}
Console.WriteLine($"{syncedFiles.Count} files got synced!");
}
catch (Exception ex)
{
Console.WriteLine("");
Console.WriteLine(ex.Message);
Console.WriteLine("");
}
finally
{
con.Disconnect();
}
}
}
If you are looking for other ways to build the file spec, like for example sync only a specific list of files to "head", etc, visit this link and search for "Building a FileSpec"
I am using EWS to create a StreamingSubscription on an inbox. It is listening for the NewMail event. I am able to pull the From Address, Subject, Body, To Address, CC Address but not the BCC Address. Is there any way to see this list?
CODE:
static void OnEvent(object sender, NotificationEventArgs args)
{
String from = null;
String subject = null;
String body = null;
String to = null;
StreamingSubscription subscription = args.Subscription;
// Loop Through All Item-Related Events
foreach (NotificationEvent notification in args.Events)
{
ItemEvent item = (ItemEvent)notification;
PropertySet propertySet = new PropertySet(ItemSchema.UniqueBody);
propertySet.RequestedBodyType = BodyType.Text;
propertySet.BasePropertySet = BasePropertySet.FirstClassProperties;
// Parse Email
EmailMessage message = EmailMessage.Bind(service, item.ItemId, propertySet);
from = message.From.Address;
subject = message.Subject;
body = message.Body.Text;
if (message.ToRecipients.Count > 0)
{
to = message.ToRecipients[0].Address;
body += "\n TO FIELD";
}
else if (message.CcRecipients.Count > 0)
{
to = message.CcRecipients[0].Address;
body += "\n CC FIELD";
}
/************** Does not work! BccRecipients is always empty *****************/
else if (message.BccRecipients.Count > 0)
{
to = message.BccRecipients[0].Address;
body += "\n BCC FIELD";
}
/************* REST OF CODE ************************/
}
}
That would kind of defeat the point of a blind-carbon-copy. I dont believe it can be done.
Consider using the Journaling feature of Exchange. This uses something called "Envelope Journaling" which includes BCC information for messages within the Exchange environment.
For everything that comes from external sources (gmail) no BCC information is available.
This might help:
http://gsexdev.blogspot.com/2011/06/processing-bccs-in-exchange-transport.html
I am using the below code, and it only sends one email - I have to send the email to multiple addresses.
For getting more than one email I use:
string connectionString = ConfigurationManager.ConnectionStrings["email_data"].ConnectionString;
OleDbConnection con100 = new OleDbConnection(connectionString);
OleDbCommand cmd100 = new OleDbCommand("select top 3 emails from bulk_tbl", con100);
OleDbDataAdapter da100 = new OleDbDataAdapter(cmd100);
DataSet ds100 = new DataSet();
da100.Fill(ds100);
for (int i = 0; i < ds100.Tables[0].Rows.Count; i++)
//try
{
string all_emails = ds100.Tables[0].Rows[i][0].ToString();
{
string allmail = all_emails + ";";
Session.Add("ad_emails",allmail);
Response.Write(Session["ad_emails"]);
send_mail();
}
}
and for sending the email I use:
string sendto = Session["ad_emails"].ToString();
MailMessage message = new MailMessage("info#abc.com", sendto, "subject", "body");
SmtpClient emailClient = new SmtpClient("mail.smtp.com");
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("abc", "abc");
emailClient.UseDefaultCredentials = true;
emailClient.Credentials = SMTPUserInfo;
emailClient.Send(message);
The problem is that you are supplying a list of addresses separated by semi-colons to the MailMessage constructor when it only takes a string representing a single address:
A String that contains the address of the recipient of the e-mail message.
or possibly a list separated by commas (see below).
Source
To specify multiple addresses you need to use the To property which is a MailAddressCollection, though the examples on these pages don't show it very clearly:
message.To.Add("one#example.com, two#example.com"));
The e-mail addresses to add to the MailAddressCollection. Multiple e-mail addresses must be separated with a comma character (",").
MSDN page
so creating the MailMessage with a comma separated list should work.
This is what worked for me.
(recipients is an Array of Strings)
//Fuse all Receivers
var allRecipients = String.Join(",", recipients);
//Create new mail
var mail = new MailMessage(sender, allRecipients, subject, body);
//Create new SmtpClient
var smtpClient = new SmtpClient(hostname, port);
//Try Sending The mail
try
{
smtpClient.Send(mail);
}
catch (Exception ex)
{
Log.Error(String.Format("MailAppointment: Could Not Send Mail. Error = {0}",ex), this);
return false;
}
This function validates a comma- or semicolon-separated list of email addresses:
public static bool IsValidEmailString(string emailAddresses)
{
try
{
var addresses = emailAddresses.Split(',', ';')
.Where(a => !string.IsNullOrWhiteSpace(a))
.ToArray();
var reformattedAddresses = string.Join(",", addresses);
var dummyMessage = new System.Net.Mail.MailMessage();
dummyMessage.To.Add(reformattedAddresses);
return true;
}
catch
{
return false;
}
}
To send to multiple recipients I set up my recipient string with a comma as my separator.
string recipient = "foo#bar.com,foo2#bar.com,foo3#bar.com";
Then to add the recipients to the MailMessage object:
string[] emailTo = recipient.Split(',');
for (int i = 0; i < emailTo.GetLength(0); i++)
mailMessageObject.To.Add(emailTo[i]);
This code I use for send multiple mail for to, bcc and cc
MailMessage email = new MailMessage();
Attachment a = new Attachment(attach);
email.From = new MailAddress(from);//De
string[] Direcciones;
char[] deliminadores = { ';' };
//Seleccion de direcciones para el parametro to
Direcciones = to.Split(deliminadores);
foreach (string d in Direcciones)
email.To.Add(new MailAddress(d));//Para
//Seleccion de direcciones para el parametro CC
Direcciones = CC.Split(deliminadores);
foreach (string d in Direcciones)
email.CC.Add(new MailAddress(d));
//Seleccion de direcciones para el parametro Bcc
Direcciones = Bcc.Split(deliminadores);
foreach (string d in Direcciones)
enter code here`email.Bcc.Add(new MailAddress(d));
You are also allowed to pass MailMessage.To.Add()a comma separated list of valid RFC 822 e-mail addresses:
Nathaniel Borenstein <nsb#bellcore.com>, Ned Freed <ned#innosoft.com>
So the code would be:
message.To.Add("Nathaniel Borenstein <nsb#bellcore.com>, Ned Freed <ned#innosoft.com>");
Note: Any code released into public domain. No attribution required.