IMAP using c# - AE.Net.Mail - c#

I have been trying to use the solution provided in the following link:
using c# .net librarires to check for IMAP messages from gmail servers
But I keep hitting the error:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Is there something that I am missing here. My Code:
public List<MailMessage> ReadMail()
{
List<MailMessage> msgs;
using (var ic = new AE.Net.Mail.ImapClient("imap.gmail.com", "username#gmail.com", "pass-to-gmail", ImapClient.AuthMethods.Login, 993, true))
{
ic.SelectMailbox("INBOX");
msgs = new List<MailMessage>(ic.GetMessageCount());
msgs = ic.GetMessages(0, 100, false, true).ToList();
ic.Disconnect();
}
return msgs;
}

Use this piece of code to connect to gmail.
ImapX.ImapClient client = null;
client = new ImapX.ImapClient("imap.gmail.com", 993, true);
if (!client.Connection())
{
MessageBox.Show("Couldn't connect to gmail. Check your internet connection and try again");
client = null;
return false;
}
if (!client.LogIn(email, password))
{
MessageBox.Show("Email And/Or password incorrect");
client = null;
return false;
}

Related

How to connect mqtt with websocket in c#?

I tried use MQTTnet to connect mqtt.
But seems not worked, it would show the error message:
Unable to connect the remote server, the request was aborted: Could not create SSL/TLS secure channel.
I also found error message on windows event:
A fatal alert was received from the remote endpoint. The TLS protocol defined fatal alert code is 40.
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Options;
public override void Run()
{
var option = new MqttClientOptionsBuilder()
.WithWebSocketServer("wss://mymqttserver:443")
.WithClientId(Guid.NewGuid().ToString())
.WithTls(new MqttClientOptionsBuilderTlsParameters()
{
AllowUntrustedCertificates = true,
UseTls = true,
SslProtocol = SslProtocols.Tls12,
CertificateValidationCallback = delegate { return true; },
})
.WithCleanSession()
.Build();
var mqtt = new MqttFactory().CreateMqttClient() as MqttClient;
mqtt.ConnectAsync(option).Wait();
string convertMsg = JsonConvert.SerializeObject("Mqtt Connect Successfully!!");
var appMsg = new MqttApplicationMessage();
appMsg.Payload = Encoding.UTF8.GetBytes(convertMsg);
appMsg.Topic = "myTopic";
appMsg.QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce;
appMsg.Retain = false;
mqttClient.PublishAsync(appMsg).Wait();
}
I also tried connect my mqtt server with third party application.
It can connect successfully, so my mqtt server should be okay.
But I don't know why I can't use c# to connect.
In the line
.WithWebSocketServer("wss://mymqttserver:443")
You must remove the "wss://" because that is already being specified using the method ".WithWebSocketServer". So, you would have
.WithWebSocketServer("mymqttserver:443")
Just use the server and the port.

Trying to send SMTP email - connection refused

I am trying to send an email to MailTrap.io its a free smtp portal for checking the email but im getting the following error.
I am using MailKit to send the email
https://mailtrap.io
public async Task SendEmailAsync(string email, string subject, string message)
{
try
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("David", "davidnoreply#gmail.com"));
emailMessage.To.Add(new MailboxAddress("", email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart("HTML") { Text = message };
using (var client = new SmtpClient())
{
client.LocalDomain = "http://localhost:52101";
await client.ConnectAsync("smtp.mailtrap.io", 584, true);
client.Authenticate("16729fdfa173b4", "0e6de61c67b069");
client.Send(emailMessage);
//await client.emailMessage(emailMessage).ConfigureAwait(false);
//await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
catch (Exception ex)
{
// TODO: handle exception
throw new InvalidOperationException(ex.Message);
}
}
But the following error presents itself I have tried on port 25 but then i get an error about ssl.
No connection could be made because the target machine actively
refused it. 127.0.0.1:25
If I change it to port 25 I get the following.
An error occurred while attempting to establish an SSL or TLS connection.
This usually means that the SSL certificate presented by the server is not trusted by the system for one or more of
the following reasons:
1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
3. A Certificate Authority CRL server for one or more of the certificates in the chain is temporarily unavailable.
4. The certificate presented by the server is expired or invalid.
Another possibility is that you are trying to connect to a port which does not support SSL/TLS.
It is also possible that the set of SSL/TLS protocols supported by the client and server do not match.
See https://github.com/jstedfast/MailKit/blob/master/FAQ.md#SslHandshakeException for possible solutions.
Edit 2
I removed the ssl but stil the same error above.
public async Task SendEmailAsync(string email, string subject, string message)
{
try
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("David", "david#gmail.com"));
emailMessage.To.Add(new MailboxAddress("", email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart("HTML") { Text = message };
using (var client = new SmtpClient())
{
await client.ConnectAsync("smtp.mailtrap.io", 25, true);
client.Authenticate("16729fdfa173b4", "0e6de61c67b069");
client.Send(emailMessage);
//await client.emailMessage(emailMessage).ConfigureAwait(false);
//await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
catch (Exception ex)
{
// TODO: handle exception
throw new InvalidOperationException(ex.Message);
}
}

Can't connect to Gmail with IMAPX using c#

I'm following an example from IMAPX but it will not connect to GMAIL.
IMAP is enabled for the account and I've triple checked the username and password but it won't connect:
var server = ConfigurationManager.AppSettings["server"];
var login = Decrypt(ConfigurationManager.AppSettings["user"]);
var password = Decrypt(ConfigurationManager.AppSettings["pass"]);
//create the IMAP CLient
var client = new ImapClient(server, true);
//connect to the server
if (!client.Connect())
{
Console.WriteLine("Error: Failed to connect");
return;
}
//login to the server
if (!client.Login(login, password))
{
Console.WriteLine("Error: Invalid login");
return;
}
Anyone have any idea how to use this library to connect to gmail? I have tried variations of "use SSL" and "verify certificate", but no mater what I try the login always fails.
Google by default does not allow "less secure" apps from account access unless the account is setup to allow it.
References:
https://support.google.com/accounts/answer/6010255?hl=en
https://security.stackexchange.com/questions/66025/what-are-the-dangers-of-allowing-less-secure-apps-to-access-my-google-account

Getting unread count from gmail using C#

I've been trying to get the count of unread emails in Gmail but I'm encountering some problems. I did a search and I found ImapX library that should help me achieve this, but the code I found here on StackOverFlow on previews questions doesn't work. This is my code right now:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string username = "my_email#gmail.com";
string passwd = "my_pass";
int unread = 0;
ImapClient client = new ImapClient("imap.gmail.com", 993, true);
bool result = client.IsConnected;
if (result)
Console.WriteLine("Connection Established");
result = client.Login(username, passwd); // <-- Error here
if (result)
{
Console.WriteLine("Logged in");
FolderCollection folders = client.Folders;
// Message messages = client.Folders["INBOX"].Messages;
foreach (ImapX.Message m in client.Folders["INBOX"].Messages)
{
if (m.Seen == false)
unread++;
}
Console.WriteLine(unread);
}
}
}
}
The Error is:
The selected authentication mechanism is not supported" on line 26
which is result = client.Login(username, passwd);
Sample from ImapX:
var client = new ImapX.ImapClient("imap.gmail.com", 993, true);
client.Connection();
client.LogIn(userName, userPassword);
var messages = client.Folders["INBOX"].Search("ALL", true);
Maybe you have enabled Two-factor authentication and you need generate application password. Othery way you will receive an e-mail warning that something is trying to access your mailbox and you must add your application as an exception. As an alternate solution you can try https://github.com/jstedfast/MailKit sample code at the bottom of the README
Most likely, gmail is looking for you to do a STARTTLS command, which it appears ImapX does not support. If you look at the response to the IMAPX1 CAPABILITY request, you'll likely see a "LOGINDISABLED" element, which means the server won't accept the "LOGIN" statement yet. So even if you UseSSL, the server (Microsoft Exchange in my case) is still looking for the STARTTLS command before it will let me LOGIN.
You have to make the connection.
ImapClient client = new ImapClient("imap.gmail.com", 993, true);
client.Connect();
bool result = client.IsConnected;
So if you added the line client.Connect(), I think it solves your problem.

AE.Net.Mail not able to connect to outlook.office365.com IMAP

I am finding that I am unable to connect to outlook.office365.com's IMAP server using AE.Net.Mail. The code is very simple:
this._imapClient = new ImapClient(imapServer, username, password, AE.Net.Mail.AuthMethods.Login, port, enableSSL)
I find that I can connect to GMail with no issues, but office365 outlook will not connect, I keep getting timeouts. I've verified the IMAP settings by putting them in to Outlook and in to Thunderbird.
Has anyone else had trouble connecting AE.Net.Mail to Office365's IMAP server?
AE.Net.Mail is quite buggy and has not seen any development in over a year last I checked. I would recommend using MailKit instead.
I just confirmed that MailKit works with Office365.com with the following code snippet:
using (var client = new ImapClient ()) {
client.Connect ("outlook.office365.com", 993, true);
client.Authenticate ("username", "password");
// get the unread messages
var uids = client.Inbox.Search (SearchQuery.NotSeen);
foreach (var uid in uids) {
var message = client.Inbox.GetMessage (uid);
}
client.Disconnect (true);
}
Hope that helps.
Found I am able to connect by increasing the timeouts:
_imapClient.ServerTimeout = 120000;
_imapClient.IdleTimeout = 120000;
_imapClient.Connect(_imapServer, _port, _enableSSL, false);
_imapClient.Login(_username, _password);
_imapClient.SelectMailbox("Inbox");

Categories