aspnetboiletplate - send email with attachments - email

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

Related

Capture HTML Form Responses in Google Sheets and send a Confirmation Email to the Form Submitter

I want the script to send the created html email template email.html to the person who last submitted the form.
Below is the success message I get in the console:
Below is the actual email that is received by the person who submits the form:
The email.html is formatted correctly and appears perfectly when sent manually.
I hope this is reprex enough.
EDIT: Maybe it's easier if I include the code
function sendEmail () {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var data = ss.getRange(lr,3);
var email = data.getValue();
var message = HtmlService.createTemplateFromFile('email');
var subject = "Test Subject"
GmailApp.sendEmail(email,subject, message);
}
It's not clear why you are using HtmlService.createTemplateFromFile, but from the image it's clear there at least one error, the script misses two methods:
HtmlService.HtmlTemplate.evaluate() to evaluate the Templated HTML
HtmlService.HtmlOutput.getContent() to get the HTML from the HtmlService.HtmlOutput object returned by the previous method.
Another option that looks to be an error is the use of GmailApp.sendEmail(string,string,string) method, as the third parameter should be a string to be used as the email plain text content. If you want to pass HTML, instead use GmailApp.sendEmail(string,string,string, Object)
Related
Emailing Google Sheet range (with or without formatting) as a HTML table in a Gmail message
Sending an email in HTML and plain with a Gmail Apps Script
Google script inject html into html email
References
https://developers.google.com/apps-script/guides/html
https://developers.google.com/apps-script/guides/html/templates
https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String)

MVC5 Mailkit send email with incorrect Email address

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.

Username is getting appended to From address while sending mail using Mailkit

I am using the following code for sending mail using mailkit in dot net core.
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Joey Tribbiani", "noreply#localhost.com"));
message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "mymail#gmail.com"));
message.Subject = "How you doin'?";
message.Body = new TextPart("plain"){ Text = #"Hey" };
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587);
client.Authenticate("mymail#gmail.com", "mypassword");
client.Send(message);
client.Disconnect(true);
}
I am using smtp client which requires authentication.
Once i receive a mail, the FROM address in that mail is mymail#gmail.com which is the username used to connect to that host, but not noreply#localhost.com which is actual FROM address.
The other option is username gets appended to the actual FROM address.
Example- noreply#localhost.com[mailto:mymail#gmail.com]
Can someone provide a solution to control this?
This is not a problem with MailKit, it's simply a feature of GMail. This is an attempt by Google to prevent spoofing emails.

Microsoft.Exchange.WebServices.Data.ServiceResponseException: When Sending Emails

I am using EWS Managed API to send email.
I am getting a Microsoft.Exchange.WebServices.Data.ServiceResponseException: EmailAddress or ItemId must be included in the request.
In the Soap return XML I see ErrorMissingInformationEmailAddress : This error occurs if the EmailAddress (NonEmptyStringType) element is missing.
Which email address is it talking about?
Using Exchange 2007 SP1.
Exchange credentials are correct and the to/from email addresses are valid emails.
Any ideas? Google has not helped.
Same code has worked for other Exchange Servers.
service.AutodiscoverUrl() does not work for this server.
using Microsoft.Exchange.WebServices.Data;
protected void SendEwsMail()
{
//Trust all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);
var service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new NetworkCredential("user#domain.com", "password");
service.Url = new Uri("Url");
var email = new EmailMessage(service);
email.ToRecipients.Add("user#domain.com");
email.From = new EmailAddress("user#domain.com");
//email.ReplyTo.Add(recipient.FromAddress);
email.Sender = new EmailAddress("user#domain.com");
email.Subject = "test";
// Send the message and save a copy.
email.SendAndSaveCopy();
}
It turns out that for the mail Server (MS Exchange) in question I needed to use this method:
Writing an encrypted mail via Exchange Web Services
var item = new EmailMessage(service);
item.MimeContent = new MimeContent(Encoding.ASCII.HeaderName, content);
// Set recipient infos, etc.
item.Send();
It seems to be because of the encrypyed MIME attachment. Using the standard To, From, Subject properties of the Microsoft.Exchange.WebServices.Data.EmailMessage class does not work correctly.
Although it does work as expected when the mail server was SmarterMail.
SmarterMail 9.x is one of the only mail servers (including Microsoft Exchange) to support Exchange Web Services (EWS).
(from http://blogs.smartertools.com/tag/exchange-web-services/)
Anyone know why SmarterMail would behave differently to MS Exchange?

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 :)