Im trying to find a method in mailkit that executes the command "Execute append" in IMAP, in C# i would do it like:
MailMessage mg = null;
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
//Add Draft
var smg = new SmtpMessage("xxx#gmail.com", "yyy#hotmail.com","yyy#hotmail.com", "This is a test mail.", "Hi.Is it correct??");
cl.ExecuteAppend("GMail/Drafts", smg.GetDataText(), "\\Draft",DateTimeOffset.Now);
}
}
However observing MailKit ImapClient, i dont have this option..
How can i execute append in MailKit IMAP?
After some hours searching....
using (var client = new ImapClient())
{
try
{
client.Connect(ConfigurationManager.AppSettings["ImapServer"], int.Parse(ConfigurationManager.AppSettings["ImapPort"]), SecureSocketOptions.Auto);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// MailKit uses by default ntlm authentication
client.Authenticate("username", "password");
var draftFolder = client.GetFolder(SpecialFolder.Drafts);
if (draftFolder != null)
{
draftFolder.Open(FolderAccess.ReadWrite);
draftFolder.Append(message, MessageFlags.Draft);
draftFolder.Expunge();
}
else
{
var toplevel = client.GetFolder(client.PersonalNamespaces[0]);
var DraftFolder = toplevel.Create(SpecialFolder.Drafts.ToString(), true);
DraftFolder.Open(FolderAccess.ReadWrite);
DraftFolder.Append(message, MessageFlags.Draft);
DraftFolder.Expunge();
}
}
catch (Exception ex)
{
throw new ApplicationException("IMAPException has occured: " + ex.Message);
}
client.Disconnect(true);
}
Related
I want to fetch the details from my outlook mailbox but don't have the Microsoft exchange server. I only have cloud-based services.
I tried to use the below-given code but that is an exchange server API solution. The second method is to open the outlook app and then accessing the mailbox but doesn't want this solution.
try
{
'Mailbox credentials'
string emailAddress = AppSettings.Office365EmailAddress;
string password = AppSettings.Office365Password;
ServicePointManager.ServerCertificateValidationCallback =
CertificateValidationCallBack;
ExchangeService service = new
ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new WebCredentials(emailAddress, password);
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
service.PreAuthenticate = true;
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress,
emailAddress);
ItemView view = new ItemView(int.MaxValue);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox,
SetFilter(), view);
DataTable dtEmails = GenerateEmailDataTable();
DataRow dr = dtEmails.NewRow();
foreach (Item item in findResults.Items)
{
if (item.Subject != null)
{
Match match = Regex.Match(item.Subject.ToString(), regJMSNumber);
if (match != null)
{
dr["EmailTo"] = item.DisplayTo.ToString();
dr["EmailFrom"] = item.DisplayTo.ToString();
dr["EmailCC"] = item.DisplayCc.ToString();
dr["EmailBCC"] = item.DisplayTo.ToString();
dr["EmailSubject"] = item.Subject.ToString();
dr["EmailBody"] = item.Body.ToString();
dr["CreatedOn"] = item.Subject.ToString();
dr["IsActive"] = true;
}
else
{
Console.WriteLine("Subject Not Match");
}
}
}
}
'Error handler.'
catch (System.Exception e)
{
Console.WriteLine("{0} Exception caught: ", e);
}
finally
{
}
Another approach is the Power Automate option but I want to do it programmatically.
Used https://outlook.office365.com/EWS/Exchange.asmx API.
When I am using EWS (exchange API), the application throwing a 401 Unauthorised requests failed exception.
Please tell me any other way to track the outlook emails with all details like EmailTo, EmailSent, EmailSubject, EmailBody, EmailCC, EmailBCC, and all the trailing messages.
I am trying to connect tls enabled dgraph server using c# .net for that I have written below console application
class DGraphClient
{
public IDgraphClient GetDgraphClient()
{
GraphSchemaIOConnection ConnectionConfig1 = new GraphSchemaIOConnection();
ConnectionConfig1.Endpoint = "testdgraph.abc.tech:9080";
DgraphInstance GSioDgraph = new DgraphInstance();
DgraphCertificates certificates = new DgraphCertificates();
certificates.CaCert = "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURVekNDQWp1Z0F3SUJBZ0lJR1dnMnhpbzVMYVl3RFFZSkt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Mk1neVZobGZuWFIxeWwrUXJiNwovY0FsN3RpR0kvcmJDZFYvVFpLTVJHN0ZyUVFUK0p2NFErbTlKT0EwNldWMTYrTU5ZNXAwCi0tLS0tRU5EIFJTQSBQUklWQVRFIEtFWS0tLS0tCg";
GSioDgraph.Certificates = certificates;
GSioDgraph.Address = "testdgraph.abc.tech:9080";
if (ConnectionConfig1.Endpoint.Equals("localhost"))
{
var client = DgraphDotNet.Clients.NewDgraphClient();
client.Connect("");
return client;
}
else
{
var client = DgraphDotNet.Clients.NewDgraphClient();
var caCert = GSioDgraph.Certificates.CaCert;
var clientCert = GSioDgraph.Certificates.ClientCert;
var clientKey = GSioDgraph.Certificates.ClientKey;
var tls = new SslCredentials(caCert, new KeyCertificatePair(clientCert, clientKey));
client.Connect(GSioDgraph.Address, tls);
// var result = client.CheckVersion();
return client;
}
}
and calling check version using below code
DGraphClient dc = new DGraphClient();
try
{
var dgraphClient = dc.GetDgraphClient();
var result1 = await dgraphClient.CheckVersion();
if (result1.IsSuccess)
{
Console.WriteLine("Connected to Dgraph version {Version}", result1.Value);
}
var res = await dgraphClient.Query(query);//.NewTransaction().Query(query);
if (res.IsFailed)
{
Console.WriteLine("ERROR THROWING");
}
result = res.Value;
await dgraphClient.NewTransaction().Commit();
}
catch (Exception ex)
{
throw ex;
}
after instanciate client I am just checking server version to make sure its connected but failed with grpc {Result: IsSuccess='False', Reasons='ExceptionalError with Message='Status(StatusCode=Unavailable, Detail="Empty update")', Exception='Grpc.Core.RpcException: Status(StatusCode=Unavailable, Detail="Empty update")\r\n at DgraphDotNet.GRPCConnection.CheckVersion()\r\n at DgraphDotNet.DgraphClient.CheckVersion()'', }
I've written a mail method and I'm setting the from email address but when the customer receives it, it's the same as the username that is used to authenticate the email.
I've tried to set the email right before the send and it still comes out wrong:
When I check the message, as shown above, the from is correct but the customer receives it from the username field instead.
public static EmailResults SendEmail(EmailSettings emailSettings)
{
var emailResults = new EmailResults();
try
{
// using mimekit that the msdn smtpclient webpage suggested using
// http://www.mimekit.net/docs/html/Introduction.htm
if (emailSettings.TestModeEnabled)
{
emailResults.IsSuccessful = true;
emailResults.Message = "SendEmail disabled due to TestModeEnabled being set to true.";
return emailResults;
}
// use the mimemessage to create the message to send
var message = new MimeMessage();
message.From.Add(emailSettings.FromEmail);
message.Subject = emailSettings.EmailSubject;
// to email has the option for multiple emails to be sent to
// loop through them and add them all to the message
foreach (var mailboxAddress in emailSettings.ToEmail)
{
message.To.Add(mailboxAddress);
}
// attach file if present
var builder = new BodyBuilder();
if (emailSettings.FileAttachments != null)
{
foreach (var file in emailSettings.FileAttachments)
{
if (File.Exists(file))
{
builder.Attachments.Add(file);
}
}
}
builder.HtmlBody = emailSettings.EmailBody;
message.Body = builder.ToMessageBody();
//// http://www.mimekit.net/docs/html/Creating-Messages.htm
//// A TextPart is a leaf-node MIME part with a text media-type. The first argument to the
//// TextPart constructor specifies the media-subtype, in this case, plain. Another media
//// subtype you are probably familiar with is the html subtype. Some other examples
//// include enriched, rtf, and xml.
//message.Body = new TextPart("html")
//{
// Text = emailSettings.EmailBody
//};
// bcc has the option for multiple emails to be sent to
// loop through them and add them all to the message
if (emailSettings.BccEmail != null)
{
foreach (var mailboxAddress in emailSettings.BccEmail)
{
message.Bcc.Add(mailboxAddress);
}
}
// *************** SEND EMAIL *******************
var client = emailSettings.EnableSmtpLog ? new MailKit.Net.Smtp.SmtpClient(new ProtocolLogger(GlobalVariables.SmptpLogFile)) : new MailKit.Net.Smtp.SmtpClient();
using (client)
{
if (emailSettings.SmtpServer.Contains("gmail.com"))
{
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
}
client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
//accept all SSL certificates
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
// client.Connect(emailSettings.SmtpServer, emailSettings.SmtpPort, emailSettings.IsSslEnabled);
client.Connect(emailSettings.SmtpServer, emailSettings.SmtpPort, emailSettings.AuthType);
if (emailSettings.IsAuthenticationRequired)
{
// Note: only needed if the SMTP server requires authentication
client.Authenticate(emailSettings.SmtpUsername, emailSettings.SmtpPassword);
}
if (emailSettings.TimeOut == 0) emailSettings.TimeOut = 10;
client.Timeout = emailSettings.TimeOut * 1000;
//message.From.Add(new MailboxAddress("someone#somewhere.net"));
client.Send(message);
client.Disconnect(true);
}
// if we reached this far, then the email was sent successfully
emailResults.Message = "Successfully sent.";
emailResults.IsSuccessful = true;
return emailResults;
}
catch (AuthenticationException e)
{
Logging.LogException("SmtpClient.SendEmail", "Error attempting to send email.", e);
emailResults.IsSuccessful = false;
emailResults.Message = "Invalid username or password.";
return emailResults;
}
catch (Exception e)
{
Logging.LogException("SmtpClient.SendEmail", "Error attempting to send email.", e);
emailResults.IsSuccessful = false;
if (e.Message.Contains("error occurred while attempting to establish an SSL or TLS connection"))
{
emailResults.Message = "An error occurred while attempting to establish a secure connection.\r\n\r\nPlease check your email settings.";
}
else
{
emailResults.Message = e.Message;
}
return emailResults;
}
}
Anyone have any suggestions on what I'm doing wrong?
For anyone who runs in to this again...
This particular issue is specific to Gmail. I'm not sure if other email hosts do the same.
If you are setting the from email address to "person1#email.com" but authenticating with "person2#gmail.com", Gmail will override the from email address with the authentication email address. You have no control over this.
Go to the Gmail account, into settings, and add the alias address in the "Send Mail As" section. The outgoing email should now display with the alias address rather than the authenticating address.
I'm creating an app that access the Microsoft Cloud API to get health data. It uses OAuth to log in when you hit the Sign In Button
private void signinButton_Click(object sender, RoutedEventArgs e)
{
UriBuilder uri = new UriBuilder("https://login.live.com/oauth20_authorize.srf");
var query = new StringBuilder();
query.AppendFormat("redirect_uri={0}", Uri.EscapeDataString(RedirectUri));
query.AppendFormat("&client_id={0}", Uri.EscapeDataString(ClientId));
query.AppendFormat("&scope={0}", Uri.EscapeDataString(Scopes));
query.Append("&response_type=code");
uri.Query = query.ToString();
this.webView.Visibility = Visibility.Visible;
this.webView.Navigate(uri.Uri);
}
This brings up a webView with the page to log in using Microsoft credentials. Once completed, it leads to this:
private async void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
//
// When the web view navigates to our redirect URI, extract the authorization code from
// the URI and use it to fetch our access token. If no authorization code is present,
// we're completing a sign-out flow.
//
if (args.Uri.LocalPath.StartsWith("/oauth20_desktop.srf", StringComparison.OrdinalIgnoreCase))
{
WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(args.Uri.Query);
var code = decoder.FirstOrDefault((entry) => entry.Name.Equals("code", StringComparison.OrdinalIgnoreCase));
var error = decoder.FirstOrDefault((entry) => entry.Name.Equals("error", StringComparison.OrdinalIgnoreCase));
var errorDesc = decoder.FirstOrDefault((entry) => entry.Name.Equals("error_description", StringComparison.OrdinalIgnoreCase));
// Check the code to see if this is sign-in or sign-out
if (code != null)
{
// Hide the browser again, no matter what happened...
sender.Visibility = Visibility.Collapsed;
if (error != null)
{
this.responseText.Text = string.Format("{0}\r\n{1}", error.Value, errorDesc.Value);
return;
}
var tokenError = await this.GetToken(code.Value, false);
if (string.IsNullOrEmpty(tokenError))
{
this.responseText.Text = "Successful sign-in!";
this.signoutButton.IsEnabled = true;
this.signinButton.IsEnabled = false;
this.getProfileButton.IsEnabled = true;
this.getDevicesButton.IsEnabled = true;
this.getActivitiesButton.IsEnabled = true;
this.getDailySummaryButton.IsEnabled = true;
this.getHourlySummaryButton.IsEnabled = true;
}
else
{
this.responseText.Text = tokenError;
}
}
else
{
this.responseText.Text = "Successful sign-out!";
this.signoutButton.IsEnabled = false;
this.signinButton.IsEnabled = true;
this.getProfileButton.IsEnabled = false;
this.getDevicesButton.IsEnabled = false;
this.getActivitiesButton.IsEnabled = false;
this.getDailySummaryButton.IsEnabled = true;
this.getHourlySummaryButton.IsEnabled = false;
}
}
}
private async Task<string> GetToken(string code, bool isRefresh)
{
UriBuilder uri = new UriBuilder("https://login.live.com/oauth20_token.srf");
var query = new StringBuilder();
query.AppendFormat("redirect_uri={0}", Uri.EscapeDataString(RedirectUri));
query.AppendFormat("&client_id={0}", Uri.EscapeDataString(ClientId));
query.AppendFormat("&client_secret={0}", Uri.EscapeDataString(ClientSecret));
if (isRefresh)
{
query.AppendFormat("&refresh_token={0}", Uri.EscapeDataString(code));
query.Append("&grant_type=refresh_token");
}
else
{
query.AppendFormat("&code={0}", Uri.EscapeDataString(code));
query.Append("&grant_type=authorization_code");
}
uri.Query = query.ToString();
var request = WebRequest.Create(uri.Uri);
try
{
using (var response = await request.GetResponseAsync())
{
using (var stream = response.GetResponseStream())
{
using (var streamReader = new StreamReader(stream))
{
var responseString = streamReader.ReadToEnd();
var jsonResponse = JObject.Parse(responseString);
this.creds.AccessToken = (string)jsonResponse["access_token"];
this.creds.ExpiresIn = (long)jsonResponse["expires_in"];
this.creds.RefreshToken = (string)jsonResponse["refresh_token"];
string error = (string)jsonResponse["error"];
return error;
}
}
}
}
catch (Exception ex)
{
return ex.Message;
}
}
I don't want users to have to accept the permissions every time the app is launched. Is there a way to save credentials locally so that it automatically authenticates on launch? Thanks!
You can use
Windows.Storage.ApplicationData.Current.LocalSettings
This process good described by this answer Best Way to keep Settings for a WinRT App?
The code in link identity to UWP
Store the needed oauth parts in the credential locker API. Never store these kind of information in the normal settings API.
On start read the oauth information and use the refreshtoken to get a new access token.
More Information here.
https://msdn.microsoft.com/en-us/library/windows/apps/mt270189.aspx
I am working on an MVC5 project, the client is interested in using MailChimp for sending emails. I have explored the MailChimp and wrappers ( MailChimp.NET ) and tried in my project as well. I tested the REST API as well and it seems to work , for example; I was able to grab lists and templates using REST API. But, still I am having issues with sending email through MailChimp.
So far, I have tried the following code and its working. Now I want to send an email to a newly registered user. Kindly give me detailed code example that How can I achieve this, because I am totally struck here..
var apiKey = "myapikey-us11";
var listId = "mylistid";
var subscribeRequest = new
{
apikey = apiKey,
id = listId,
email = new
{
email = "muhammad.waqas#seventechnology.co.uk"
},
double_optin = true,
};
var requestJson = JsonConvert.SerializeObject(subscribeRequest);
var reqresult = CallMailChimpApi("lists/", requestJson);
CallMailChimApi
private static string CallMailChimpApi(string method, string requestJson)
{
var endpoint = String.Format("https://{0}.api.mailchimp.com/3.0/{1}", "us11", method);
var wc = new WebClient();
try
{
return wc.UploadString(endpoint, requestJson);
}
catch (WebException we)
{
using (var sr = new StreamReader(we.Response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}
I Use this function and it work successfully
public void SendEmailByApiMailChimp ()
{
try
{
string UserEmail = " Exemple#gmail.com ";
MailChimpManager mc = new MailChimpManager("16d***********-us14");
EmailParameter email = new EmailParameter()
{
Email = UserEmail
};
EmailParameter resulte = mc.Subscribe("yourlistnumber", email);
var test = resulte;
}
catch (Exception ex)
{
var ters = ex;
}
}