The native MVC UserManager.sendasync works great. But when i instantiate an Email service and try to send an email ... no dice. I made a php script to send the email. Works beatuifully super easy. I also tried downloading and using Mailkit... no dice. Im not sure what to do here. No error message
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress("System", "system#my.hypertarget.io"));
mimeMessage.To.Add(new MailboxAddress("Jason", "unblockgames#gmail.com"));
mimeMessage.Subject = "Test";
mimeMessage.Body = new TextPart("plain"){Text = message};
using (var client = new SmtpClient())
{
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("relay-hosting.secureserver.net", 25, false);
client.Capabilities &= ~SmtpCapabilities.Pipelining;
client.Send(mimeMessage);
client.Disconnect(true);
}
Related
I ama able to sent SMTP emails using MailKit & MimeKit and outlook is the client tool receiving these mails. Below code has been used and my Inbox has emails received.
var email = new MimeMessage
{
Sender = MailboxAddress.Parse("<<from>>")
};
email.To.Add(MailboxAddress.Parse("<<to>>"));
email.Subject = "Test mail from Jaish";
var builder = new BodyBuilder();
builder.TextBody = "This is a test mail from Jaish Mathews";
email.Body = builder.ToMessageBody();
using var smtp = new SmtpClient();
smtp.LocalDomain = "<<domain>>";
smtp.Timeout = 10000;
smtp.Connect("<<host>>", 25, SecureSocketOptions.None);
var mailboxes = email.To.Mailboxes;
//Sending email
await smtp.SendAsync(email);
//Disconnecting from smtp
smtp.Disconnect(true);
Issue is that my "Sent" folder isn't keeping any track of these emails sent. How can I manually copy to my "Sent" folder"
Before I explain how to save the message in your Sent IMAP folder, I first want to bring attention to a few things.
smtp.Timeout = 10000; It's probably best to not override the default timeout (which I believe is 120,000. 10000 is 10 seconds).
You currently have a mix of sync and async calls to the SmtpClient. You should pick sync or async and stick with it (at least if it's all within the same method).
Okay, now on to your question.
using var imap = new ImapClient ();
await imap.ConnectAsync ("<<host>>", 143 /* or 993 for SSL */, SecureSocketOptions.Auto).ConfigureAwait (false);
await imap.AuthenticateAsync ("username", "password").ConfigureAwait (false);
IMailFolder sent = null;
if (imap.Capabilities.HasFlag (ImapCapabilities.SpecialUse))
sent = imap.GetFolder (SpecialFolder.Sent);
if (sent == null) {
// get the default personal namespace root folder
var personal = imap.GetFolder (imap.PersonalNamespaces[0]);
// This assumes the sent folder's name is "Sent", but use whatever the real name is
sent = await personal.GetSubfolderAsync ("Sent").ConfigureAwait (false);
}
await sent.AppendAsync (email, MessageFlags.Seen).ConfigureAwait (false);
await imap.DisconnectAsync (true).ConfigureAwait (false);
Am not sure whether the old method of sending Mail using Mailkit is quite working with this code below
try
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress(_emailConfig.SenderName, _emailConfig.SenderAddress));
emailMessage.To.Add(new MailboxAddress(email));
emailMessage.Subject = subject;
var builder = new BodyBuilder
{
HtmlBody = message
};
emailMessage.Body = builder.ToMessageBody();
using var smtp = new SmtpClient
{
ServerCertificateValidationCallback = (s, c, h, e) => true
};
smtp.AuthenticationMechanisms.Remove("XOAUTH2");
await smtp.ConnectAsync(_emailConfig.SmtpServer, Convert.ToInt32(_emailConfig.Port), false).ConfigureAwait(false);
await smtp.AuthenticateAsync(_emailConfig.Username, _emailConfig.Password).ConfigureAwait(false);
await smtp.SendAsync(emailMessage).ConfigureAwait(false);
await smtp.DisconnectAsync(true).ConfigureAwait(false);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
but am having exceptions if i use the code above to send email
nvalidOperationException: 534: 5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbv
5.7.14 26mzQKtlwfyEdGzHHdpi3ewWG6skAWgOBbdNNYmwzr9Sg3fGu-KixLAfODpJsVafutidE
5.7.14 8xBOp_8rNCvk9Y6iEcOkDlcZ1d-483zQ1Krw04NvqxQdq3w4iTtC8E9bL8uGprgV>
5.7.14 Please log in via your web browser and then try again.
5.7.14 Learn more at
5.7.14 https://support.google.com/mail/answer/78754 o5sm2555896wmh.8 - gsmtp
so when i changed this line of code below to use SSLS, A new error came out
await smtp.ConnectAsync(_emailConfig.SmtpServer, Convert.ToInt32(_emailConfig.Port), true).ConfigureAwait(false);
Exception returned
InvalidOperationException: 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.
have searched everywhere on how to do it,even turned on my less secured app. some recommended sendGrid, i created a free account with them also,but i dont have access to the account created. Does anyone knows how to fix the code above using Mailkit
Try it like this.
using (var smtpClient = new SmtpClient())
{
smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
await smtpClient.ConnectAsync("host", port, false);
if (smtpClient.Capabilities.HasFlag(SmtpCapabilities.Authentication))
{
smtpClient.AuthenticationMechanisms.Remove("XOAUTH2");
await smtpClient.AuthenticateAsync(username, password);
}
await smtpClient.SendAsync(mailMsg);
smtpClient.Disconnect(true);
}
I'm working in ASP.Net Core and trying to send email using smtp client from gmail. Have following code but it's not working
Have seen following post as well but it doesn't work
http://dotnetthoughts.net/how-to-send-emails-from-aspnet-core/
It thorws following error
System.NotSupportedException: The SMTP server does not support authentication
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("From Name", "fromEmail#gmail.com"));
emailMessage.To.Add(new MailboxAddress("To Name", "toEmail#gmail.com"));
emailMessage.Subject = subject;
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = message;
emailMessage.Body = bodyBuilder.ToMessageBody();
var client = new SmtpClient();
try
{
await client.ConnectAsync("smtp.gmail.com", 25, SecureSocketOptions.None).ConfigureAwait(false);
client.AuthenticationMechanisms.Remove("XOAUTH2");
await client.AuthenticateAsync("fromEmail#gmail.com", "fromPassword"); //error occurs here
await client.SendAsync(emailMessage).ConfigureAwait(false);
await client.DisconnectAsync(true);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
catch(Exception e)
{
}
The NotSupportedException is thrown because GMail does not support authentication without using an SSL/TLS connection because it only supports non-encrypted password-based authentication mechanisms.
I would recommend connecting like this:
client.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.StartTls)
Hope that helps.
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");
This question already has answers here:
Sending email through Gmail SMTP server with C#
(31 answers)
Closed 9 years ago.
I am New in Asp.net, i need to send email from Asp.net using my Outlook.
I have one button in asp and when i click button(send) i want to send email.
I tried to use Hotmail and Gmail but remote server in blocked.
If you don't understand my question please tell me.
I tried this:
var smtpClient = new SmtpClient
{
Host = "outlook.mycompany.local",
UseDefaultCredentials = false,
Credentials = new NetworkCredential("myEmail#mycommpany.com", "myPassword")
};
var message = new System.Net.Mail.MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("myemail#mycommapny.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("friendEmail#Company.com"));
// and here you're actually sending the message
smtpClient.Send(message);
}
Exeption Show: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated
Please how can i do that ?
Sending outbound email from an ASP.net web site can be problematic. Even if you get the SMTP information right, you still have to deal with:
Sender Policy Framework (SPF)
Whitelists/Blacklists
Validation
Bouncebacks
It's very difficult to do this yourself, which is why you might want to consider using a service provider instead. You simply use their API (often a REST call), and they do the rest. Here are three such providers:
SendGrid
Mandrill
Mailgun
Mandrill has a low-end free plan, and so does SendGrid if you are using it with Windows Azure. And they are all reasonably affordable, even for the larger plans.
I highly recommend using one of these with their own API instead of using System.Net.Mail yourself. But if you want, they also can act as an SMTP relay for you so you can use their SMTP servers and keep your System.Net.Mail code intact.
First of all get the company SMTP server settings (from your sys admins I guess), then you can do something like this:
// setting up the server
var smtpClient = new SmtpClient
{
Host = "your.company.smtp.server",
UseDefaultCredentials = false,
EnableSsl = true, // <-- see if you need this
Credentials = new NetworkCredential("account_to_use", "password")
};
var message = new MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("from#company.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("neo#matrix.com"));
// and here you're actually sending the message
smtpClient.Send(message);
you can use this function. and one thing you have to store you email smtp login and password in web config file
/// <summary>
/// Send Email
/// </summary>
/// <param name="strFrom"></param>
/// <param name="strTo"></param>
/// <param name="strSubject"></param>
/// <param name="strBody"></param>
/// <param name="strAttachmentPath"></param>
/// <param name="IsBodyHTML"></param>
/// <returns></returns>
public Boolean sendemail(String strFrom, string strTo, string strSubject, string strBody, string strAttachmentPath, bool IsBodyHTML)
{
Array arrToArray;
char[] splitter = { ';' };
arrToArray = strTo.Split(splitter);
MailMessage mm = new MailMessage();
mm.From = new MailAddress(strFrom);
mm.Subject = strSubject;
mm.Body = strBody;
mm.IsBodyHtml = IsBodyHTML;
//mm.ReplyTo = new MailAddress("replyto#xyz.com");
foreach (string s in arrToArray)
{
mm.To.Add(new MailAddress(s));
}
if (strAttachmentPath != "")
{
try
{
//Add Attachment
Attachment attachFile = new Attachment(strAttachmentPath);
mm.Attachments.Add(attachFile);
}
catch { }
}
SmtpClient smtp = new SmtpClient();
try
{
smtp.Host = ConfigurationManager.AppSettings["MailServer"].ToString();
smtp.EnableSsl = true; //Depending on server SSL Settings true/false
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["MailUserName"].ToString();
NetworkCred.Password = ConfigurationManager.AppSettings["MailPassword"].ToString();
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;//Specify your port No;
smtp.Send(mm);
return true;
}
catch
{
mm.Dispose();
smtp = null;
return false;
}
}
Try Amazon Simple Email Service (http://aws.amazon.com/ses/). If you're new to Amazon Web Services (AWS) there might be a learning curve. However, once you're familiar with their SDK which can be found on Nuget (AWSSDK) the process is very straight-forward (Amazon does have a lot of little wrapper classes which can be quirky).
So, to answer the question "How to send email?", it looks something like:
var fromAddress = "from#youraddress.com";
var toAddresses = new Amazon.SimpleEmail.Model.Destination("someone#somedestination.com");
var subject = new Amazon.SimpleEmail.Model.Content("Message");
var body= new Body(new Amazon.SimpleEmail.Model.Content("Body"));
var message = new Message(subject , body);
var client = ConfigUtility.AmazonSimpleEmailServiceClient;
var request= new Amazon.SimpleEmail.Model.SendEmailRequest();
request.WithSource(fromAddress)
.WithDestination(toAddresses)
.WithMessage(message );
try
{
client.SendEmail(request);
}
catch (Amazon.SimpleEmail.AmazonSimpleEmailServiceException sesError)
{
throw new SupplyitException("There was a problem sending your email", sesError);
}
You can refer to below links:
http://www.codeproject.com/Tips/371417/Send-Mail-Contact-Form-using-ASP-NET-and-Csharp
send email asp.net c#
I hope it will help you. :)