MVC5 Mailkit send email with incorrect Email address - email

I am trying to send emails using my MVC5 application. To do this, I have installed Mailkit v 1.22.0 through NuGet package manager. And this is how my code looks like:
var FromAddress = "no-reply#email.com";
var FromAddressTitle = "My Org";
var connection = ConfigurationManager.ConnectionStrings["SmtpServer"].ConnectionString;
var Email = new MimeMessage();
Email.From.Add(new MailboxAddress(FromAddressTitle, FromAddress));
var AddressArray = value.SentTo.Split(';');
foreach (var item in AddressArray)
{
Email.To.Add(new MailboxAddress(item));
}
Email.Subject = value.Subject;
Email.Body = new TextPart("html")
{
Text = value.Content
};
using (var client = new SmtpClient())
{
client.Connect(connection);
client.Send(Email);
}
return "Email Successfully Sent";
which works fine except if a wrong recipient Email address has been entered, the application does not detect if the Email was actually sent or not (client.Send(Email) returns void). Is there a way to know if it really ended up getting sent to the recipient or not? If it is not possible with Mailkit, is there any other NuGet package that can do this?

The reason that SmtpClient.Send() returns void is that the SMTP protocol does not specify whether the message gets delivered successfully. All it can do us tell the client that the messages was accepted by the server or not (in which case MailKit will throw an exception).
If you need to know whether the message was successfully delivered, you will need to check for bounce messages sent to you which could take minutes or even hours.
The first thing you'll have to do, however, is subclass SmtpClient and override the GetEnvelopeId and GetDeliveryStatusNotifications methods.
Then, when you receive a bounce message, the top-level MIME part will typically be a multipart/report (represented by a MultipartReport object when using MimeKit). This multipart/report will then contain a message/delivery-status MIME part (and possibly others), which will have a list of header-like fields that specify the details about the delivery status for 1 or more recipients.
MimeKit will parse a lot of this for you (e.g. it has a MessageDeliveryStatus class which contains a StatusGroups property that you will want to use. However, what MimeKit does not do is parse the individual field values (but they shouldn't be that difficult for you to do, typically a few Split(';')'s should be enough iirc for some quick & dirty parsing).
You will want to read the spec for this at https://www.rfc-editor.org/rfc/rfc3464
The MimeKit docs linked above specify which sections to look closely at (I think 2.2 and 2.3).
I would recommend looking specifically at the Original-Recipient and Action fields.
original-recipient-field =
"Original-Recipient" ":" address-type ";" generic-address
generic-address = *text
action-field = "Action" ":" action-value
action-value =
"failed" / "delayed" / "delivered" / "relayed" / "expanded"
You will also need the Original-Envelope-Id field to figure out which message is being reported on:
original-envelope-id-field =
"Original-Envelope-Id" ":" envelope-id
envelope-id = *text
The envelope-id text will be the same string returned by your GetEnvelopeId implementation in the SmtpClient class.

Related

aspnetboiletplate - send email with attachments

I have an aspnetboilerplate template, .netcore & angular (free version). I am trying to find a way to attach a word document to an email using the IEmailSender but cant find the proper way of doing so. Have already checked the Email Sending but there is no hint for attaching file to an email.
Does anyone have a sample code that could possibly share with me?
Here is the code snippet to send an email with attachment:
MailMessage mail = new MailMessage
{
Subject = "Subject",
Body = "Message",
IsBodyHtml = true,
To = { "toaddress#gmail.com"},
From = new MailAddress("fromaddress#gmail.com")
};
mail.Attachments.Add(new Attachment(_env.WebRootPath + "\\pp.jpg"));
_emailSender.SendAsync(mail);
You can directly construct a MailMessage and pass it to IEmailSender.SendAsync(mailMessage).
See https://github.com/aspnetboilerplate/aspnetboilerplate/blob/94ebd48fd959cd460d97b809317a959e45c94067/src/Abp/Net/Mail/EmailSenderBase.cs#L66
If you are using MailKit, the underlying implementation will convert the Mail message object into MimeMessage and send it via Mailkit
See https://github.com/aspnetboilerplate/aspnetboilerplate/blob/94ebd48fd959cd460d97b809317a959e45c94067/src/Abp.MailKit/MailKitEmailSender.cs#L42-L50
MimeMessage implementation
https://github.com/jstedfast/MimeKit/blob/bcc7030b61c0c83a10eab7e7a5d689efd923038d/MimeKit/MimeMessage.cs#L3494

Sending email to multiple recipients from UWP store app

I have a simple goal, to open up an email (in Outlook 2016) with the To field configured for multiple recipients from a Windows 10 UWP app.
I tried 3 approaches
1) The recommended way, as demod in the UWP samples, using the EmailMessage
var emailMessage = new Windows.ApplicationModel.Email.EmailMessage();
emailMessage.Body = "";
foreach (Person p in SelectedPeople)
{
if (string.IsNullOrEmpty(p.Email) == false)
{
var emailRecipient = new Windows.ApplicationModel.Email.EmailRecipient(p.Email);
emailMessage.To.Add(emailRecipient);
}
}
await Windows.ApplicationModel.Email.EmailManager.ShowComposeNewEmailAsync(emailMessage);
This results in an email window with the recipients seperate by commas which then do not resolve. Setting the option to allow comma seperators seemed like an answer, but it tuens out that doesn't work unless there is a space to seperate too?
2) Build a mailto:user1#work.com;user2#work.com URI and launch it.
var uri = new Uri("mailto:user1#work.com;user2#work.com");
var success = await Windows.System.Launcher.LaunchUriAsync(uri);
However, attempting to create URI with multiple recipeitns throws an exception that the URI hostname is invalid
3) Same as above but using the scheme mailto:?To=user1#work.com;user2#work.com
This is parsed correctly as a URI but on launch Outlook shows an empty recipient list. By way of testing, using CC= does show the recipients in the CC field
So, now I am stuck wondering how I can send an email to multiple recipients for a store app?
Late to the party, but someone linked this from another question..
Have you tied mailto:user1#work.com%3buser2#work.com
seems to work for me

titanium multiple recipients email dialog

im using titanium and need to send an email to multiple recipients. the official docs only show how to send to one individual email address.
can someone please give a more concrete example how the getToRecipients and setToRecipients methods are applied correctly so that an email is sent to multiple recipients?
https://developer.appcelerator.com/question/149943/emaildialog-gettorecipients-does-not-work
i need to pass an array (contacts) to the emailDialog.ToRecipients property:
["email#example.net","email2#example.net"]
the code below does not work with this error message (ive also tried it unsuccessfully without the "[]" in setToRecipients):
Basic functions[2807:70b]
["email#example.net","email2#example.net"]is not a valid email
address.
var emails = JSON.stringify(contacts);
var emailDialog = Ti.UI.createEmailDialog();
emailDialog.setToRecipients([emails]);
emailDialog.subject = "Hello from Titanium";
emailDialog.messageBody = '<b>Appcelerator Titanium Rocks!</b>';
emailDialog.open();
thx for any info on this!
Have you tried this?
emailDialog.setToRecipients(contacts);
The Appcelerator Documentation says that EmailDialog.toRecipients is an String [].
See u!
Why do you pass your contacts through JSON.stringify and then put it inside array with one element?
EmailDialog.setToRecipients method requires array of strings, and every single one string should be proper email address. To make it work change your code into:
var emailDialog = Ti.UI.createEmailDialog();
emailDialog.setToRecipients(contacts);
emailDialog.subject = "Hello from Titanium";
emailDialog.messageBody = "<b>Appcelerator Titanium Rocks!</b>";
emailDialog.open();
I'm assuming that contacts variable contains this array (based on your error message):
var contacts = ["email#example.net","email2#example.net"];

How to monitor delivery of emails sent by salesforce by source code?

I have following questions. Assuming I have following code
public class MessageMaker {
public static void helloMessage() {
System.debug( 'Entry point' );
Case c = new Case();
insert c;
EmailMessage e = new EmailMessage();
System.debug( 'EmailMessage created' );
e.parentid = c.id;
// Set to draft status.
// This status is required
// for sendEmailMessage().
e.Status = '5';
e.TextBody =
'Sample email message.';
e.Subject = 'Apex sample';
e.ToAddress = 'my#mail.com';
insert e;
List<Messaging.SendEmailResult>
results =
Messaging.sendEmailMessage(new ID[]
{ e.id });
System.debug(results.size());
System.debug(results[0].success);
System.debug(results[0].getErrors().size());
System.assertEquals(1, results.size());
System.assertEquals(true, results[0].success);
}
}
1.First question. I want to find out using apex code if the message was really delivered.
Here documentation says http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_sendemail_emailresult.htm
Even if success = true, it does not mean the intended recipients received the email, as it could have bounced or been blocked by a spam blocker. Also, even if the email is successfully accepted for delivery by the message transfer agent, there can still be errors in the error array related to individual addresses within the email.
So I have been trying to send email by apex code and look for results[0].success. It seems it says like it is described in documentation, so success is true even though email address was incorrect.
Also I have tried to check this manually through email logs http://eu2.salesforce.com/help/doc/en/email_logs.htm
And I have found following row in resulting log regarding my email sent to incorrect address
9/2/2013 9:36 66/FC-09306-20B54225 T julfy#i.ia
julfy=i.ua__0-6uvic1ltvun1nf#95mngihd2hpe0w.b-ysubea0.bl.bnc.salesforce.com 1434 005b0000000J7bm
<_0vTJ000000000000000000000000000000000000000000000MSHRSY00W1-CKg3DShWC5xu24ccHFA#sfdc.net>
1 311.627583 421 4.4.0 [internal] no MXs for this domain could be
reached at this time
But I don't know how to access this information by apex code. Any thoughts?
Second question. If message was delivered and recipient forwarded it, is any possibility to monitor that using apex code? Anybody?
You can't do either of those things. APEX runs on Salesforce's servers and when you send an email it leaves that environment. The only time you can monitor a successful response is when you're dealing with an API that generates webhooks.

Sending Email in DNN

I'm trying to send an email in a DNN module I'm making. However, though it doesn't crash the email isn't being sent. I think it has to do with the From Email I'm attempting to use. I'm not 100% sure what email I should be using for the from which is the first parameter.
Protected Sub Submit_Click(sender As Object, e As EventArgs) Handles Submit.Click
DotNetNuke.Services.Mail.Mail.SendEmail("support#localhost", "myemail#site.com", "EmailTest", "Hello world!")
End Sub
The More likely problem is you don't have your SMTP settings properly configured. To configure your SMTP settings, Login as Host. Then, go to Host -> Settings and fill out the fields under "SMTP Server Settings" and save them. There's a test link there as well to verify they are working correctly.
This is probably pretty late to the party, but I often use the Mail.SendMail() method, and then manually pass all the STMP information like below, and then when debugging I check the message that comes back. (As of DotNetNuke 5.5)
Dictionary<string, string> hostSettings = HostController.Instance.GetSettingsDictionary();
string server = hostSettings["SMTPServer"];
string authentication = hostSettings["SMTPAuthentication"];
string password = hostSettings["SMTPPassword"];
string username = hostSettings["SMTPUsername"];
// using the Mail.SendMail() method allows for easier debugging.
var message = Mail.SendMail(from, user.Email, String.Empty, subject, body, String.Empty, "HTML", server, authentication, username, password);
Late to the game as well, but I just ran into a similar issue earlier today...
The DNN sendMail or sendEmail method handle the exceptions on their own, and add it to their DNN logs. Unfortunately, they never return said exceptions to the main code where you are calling the functions - hence why your code executes just fine!
You can look further into their exceptions table, or Admin Logs in the UI, for more info on the particular issue you are having.
I changed my code to use System.Net to send emails and collect all of the info you need from DotNetNuke.Entities.Host.Host object in DNN. This way, we can handle the error and have our code work around it :) I ended up with something like this (it's in c# but you can do the same in VB.Net with a slightly different syntax):
//make the email
MailMessage mail = new MailMessage("From#me.com","to#a.com,to#b.com,to#c.com");
mail.Subject = "test subject";
mail.Body = "actual email";
string dnnServerInfo = DotNetNuke.Entities.Host.Host.SMTPServer;
// The above looks like "server.com:port#", or "smtp.server.com:25"
//so we find the colon to get the server name, and port using the index below
int index = dnnServerInfo.IndexOf(':');
//make the SMPT Client
SmtpClient smtp = new SmtpClient();
smtp.Host = dnnServerInfo.Substring(0, index);
smtp.Port = Int32.Parse(dnnServerInfo.Substring(index + 1, dnnServerInfo.Length - index - 1));
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(DotNetNuke.Entities.Host.Host.SMTPUsername, DotNetNuke.Entities.Host.Host.SMTPPassword);
smtp.EnableSsl = DotNetNuke.Entities.Host.Host.EnableSMTPSSL;
//send the email
smtp.Send(mail);
I used part of the original code from "SendMail" found here to come up with this: https://stackoverflow.com/a/19515503/6659531
Good luck to anybody who comes across this :)