get files from IFormFile for email attachment - email

I have an upload controller
// Multiple files upload
[HttpPost("upload/multiple")]
public IActionResult Multiple(IFormFile[] files)
{
try
{
// Put your code here
return StatusCode(200);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
I am trying to use the IFormFile to get files for email attachments using MailKit
This is my email code
private async Task SendEmail()
{
try
{
// create email message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(sender));
email.To.Add(MailboxAddress.Parse(receiver));
email.Subject = emailsubject;
var multipart = new Multipart("mixed");
multipart.Add(new TextPart(TextFormat.Html) { Text = emailMessage });
foreach (var attachment in files)
{
var content = new MemoryStream();
attachment.CopyTo(content);
content.Position = 0;
var contentType = ContentType.Parse(attachment.ContentType);
var part = new MimePart(contentType.MimeType)
{
FileName = Path.GetFileName(attachment.FileName),
ContentTransferEncoding = ContentEncoding.Base64,
Content = new MimeContent(content),
};
multipart.Add(part);
}
email.Body = multipart;
//email.Body = new TextPart(TextFormat.Html) { Text = emailMessage};
// send email
using var smtp = new SmtpClient();
smtp.Connect(outgoingServer, outgoingPort, SecureSocketOptions.Auto);
smtp.Authenticate(userName, userPassword);
smtp.Send(email);
smtp.Disconnect(true);
}
catch (Exception ex)
{
NotificationService.Notify(NotificationSeverity.Error, "Send Email Error!", ex.Message, 7000);
}
}
}
This generates an error on the 'files' variable
"The name 'files' does not exist in the current content.
Can someone tell me what I am missing to pull the information from the controller for 'files'???

Here, in the Async Task SendEmail task, we have to set the parameter of type IFormFile like below,
private async Task sendEmail(IFormFile file)
Here is the Controller Code,
[HttpPost("send")]
public async Task<IActionResult> SendMail(IFormFile file)
{
try
{
await mailService.sendEmailAsync(file);
return Ok("Mail Sent!");
}
catch (Exception ex)
{
throw;
}
}
And We can't get IFormFile[] directly and pass it to the sendEmail method as a parameter. Instead we can create the model class with public List<IFormFile>? attachments{get;set;} and send the instance of the model class as a parameter to the sendEmail method.

Related

How to get IFormFile data into stream to add as Email Attachment

I have an Email Razor page that accesses a custom method to send and email. All code seems to be correct. The problem I am having is accessing the "IFormFile files". I have tried adding the code to a controller as well as adding the IFormFile files to the custom method. I just can seem to find the right way to hande IFormFile. Below is the code that I currently have. What I am looking for is to see if someone can help me with the IFormFile portion. The information on IFormFile that I have found hasn't helped me so far as it's usually only partial information...I am very new to MVC and IFormFile, so help is greatly appreciated!
private async Task SendEmail()
{
try
{
// create email message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(sender));
email.To.Add(MailboxAddress.Parse(receiver));
email.Subject = emailsubject;
var multipart = new Multipart("mixed");
multipart.Add(new TextPart(TextFormat.Html) { Text = emailMessage });
foreach (var attachment in file)
{
var content = new MemoryStream();
attachment.CopyTo(content);
content.Position = 0;
var contentType = ContentType.Parse(attachment.ContentType);
var part = new MimePart(contentType.MimeType)
{
FileName = Path.GetFileName(attachment.FileName),
ContentTransferEncoding = ContentEncoding.Base64,
Content = new MimeContent(content),
};
multipart.Add(part);
}
email.Body = multipart;
//email.Body = new TextPart(TextFormat.Html) { Text = emailMessage};
// send email
using var smtp = new SmtpClient();
smtp.Connect(outgoingServer, outgoingPort, SecureSocketOptions.Auto);
smtp.Authenticate(userName, userPassword);
smtp.Send(email);
smtp.Disconnect(true);
}
catch (Exception ex)
{
NotificationService.Notify(NotificationSeverity.Error, "Send Email Error!", ex.Message, 7000);
}
}

How to send email with no-reply in spring-boot application

I'm trying to send emails to project managers whenever there is a change in their project staffing. For this i want to send an email from no-reply#example.com, how can i achieve this using spring boot?
Thanks in advance for the suggestions and answers.
Tried something like this:
#RequestMapping(value = "/sendEmail", method = { RequestMethod.GET }, produces = { "application/json" })
public ResponseEntity<CustomResponse> sendEmail() {
LOG.debug("Start sendEmail with data, toAddress");
HttpHeaders httpHeaders = commonUtil.setHeaders();
HttpStatus httpStatus = HttpStatus.OK;
CustomResponse customResp = new CustomResponse();
String description;
try {
String to = "bmanikanta415#gmail.com";
String from = "no-reply#example.com";
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject("Your Example.com account has been activated");
msg.setText("This is a test");
Transport.send(msg);
description = Constants.SUCCESS;
customResp = commonUtil.getCustomResponse(httpStatus, description, description);
} catch (
Exception e) {
LOG.error("Exception in sendEmail: {}", e);
description = Constants.FAILED;
customResp = commonUtil.getCustomResponse(httpStatus, description, description);
}
ResponseEntity<CustomResponse> responseEntity = new ResponseEntity<CustomResponse>(customResp, httpHeaders,
httpStatus);
LOG.debug("End sendEmail with return data: {}", responseEntity);
return responseEntity;
}

Created sendgrid email template, how to call it from Java

I have created email template in sendgrid - with substitutable values;
I get the JSON payload (contains substitute values) for processing email from rabbitMQ queue. My question is how to call the sendgrid email template from Java?
I found the solution, the way to call sendgrid template and email through sendgrid as below:
SendGrid sendGrid = new SendGrid("username","password"));
SendGrid.Email email = new SendGrid.Email();
//Fill the required fields of email
email.setTo(new String[] { "xyz_to#gmail.com"});
email.setFrom("xyz_from#gmail.com");
email.setSubject(" ");
email.setText(" ");
email.setHtml(" ");
// Substitute template ID
email.addFilter(
"templates",
"template_id",
"1231_1212_2323_3232");
//place holders in template, dynamically fill values in template
email.addSubstitution(
":firstName",
new String[] { firstName });
email.addSubstitution(
":lastName",
new String[] { lastName });
// send your email
Response response = sendGrid.send(email);
This is my working soloution .
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sendgrid.*;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class MailUtil {
public static void main(String[] args) throws IOException {
Email from = new Email();
from.setEmail("fromEmail");
from.setName("Samay");
String subject = "Sending with SendGrid is Fun";
Email to = new Email();
to.setName("Sam");
to.setEmail("ToEmail");
DynamicTemplatePersonalization personalization = new DynamicTemplatePersonalization();
personalization.addTo(to);
Mail mail = new Mail();
mail.setFrom(from);
personalization.addDynamicTemplateData("name", "Sam");
mail.addPersonalization(personalization);
mail.setTemplateId("TEMPLATE-ID");
SendGrid sg = new SendGrid("API-KEY");
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
throw ex;
}
}
private static class DynamicTemplatePersonalization extends Personalization {
#JsonProperty(value = "dynamic_template_data")
private Map<String, String> dynamic_template_data;
#JsonProperty("dynamic_template_data")
public Map<String, String> getDynamicTemplateData() {
if (dynamic_template_data == null) {
return Collections.<String, String>emptyMap();
}
return dynamic_template_data;
}
public void addDynamicTemplateData(String key, String value) {
if (dynamic_template_data == null) {
dynamic_template_data = new HashMap<String, String>();
dynamic_template_data.put(key, value);
} else {
dynamic_template_data.put(key, value);
}
}
}
}
Here is an example from last API spec:
import com.sendgrid.*;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
Email from = new Email("test#example.com");
String subject = "I'm replacing the subject tag";
Email to = new Email("test#example.com");
Content content = new Content("text/html", "I'm replacing the <strong>body tag</strong>");
Mail mail = new Mail(from, subject, to, content);
mail.personalization.get(0).addSubstitution("-name-", "Example User");
mail.personalization.get(0).addSubstitution("-city-", "Denver");
mail.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932");
SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
throw ex;
}
}
}
https://github.com/sendgrid/sendgrid-java/blob/master/USE_CASES.md
Recently Sendgrid upgraded the Maven version v4.3.0 so you don't have to create additional classes for dynamic data content. Read more from this link https://github.com/sendgrid/sendgrid-java/pull/449
If you're doing a spring-boot maven project, You'll need to add the sendgrid-java maven dependency in your pom.xml. Likewise, in your application.properties file under resource folder of the project, add SENDGRID API KEY AND TEMPLATE ID under attributes such as spring.sendgrid.api-key=SG.xyz and templateId=d-cabc respectively.
Having done the pre-setups. You can create a simple controller class as the one given below:
Happy Coding!
#RestController
#RequestMapping("/sendgrid")
public class MailResource {
private final SendGrid sendGrid;
#Value("${templateId}")
private String EMAIL_TEMPLATE_ID;
public MailResource(SendGrid sendGrid) {
this.sendGrid = sendGrid;
}
#GetMapping("/test")
public String sendEmailWithSendGrid(#RequestParam("msg") String message) {
Email from = new Email("bijay.shrestha#f1soft.com");
String subject = "Welcome Fonesal Unit to SendGrid";
Email to = new Email("birat.bohora#f1soft.com");
Content content = new Content("text/html", message);
Mail mail = new Mail(from, subject, to, content);
mail.setReplyTo(new Email("bijay.shrestha#f1soft.com"));
mail.setTemplateId(EMAIL_TEMPLATE_ID);
Request request = new Request();
Response response = null;
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
response = sendGrid.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return "Email was successfully sent";
}
}
This is based on verision com.sendgrid:sendgrid-java:4.8.3
Email from = new Email(fromEmail);
Email to = new Email(toEmail);
String subject = "subject";
Content content = new Content(TEXT_HTML, "dummy value");
Mail mail = new Mail(from, subject, to, content);
// Using template to send Email, so subject and content will be ignored
mail.setTemplateId(request.getTemplateId());
SendGrid sendGrid = new SendGrid(SEND_GRID_API_KEY);
Request sendRequest = new Request();
sendRequest.setMethod(Method.POST);
sendRequest.setEndpoint("mail/send");
sendRequest.setBody(mail.build());
Response response = sendGrid.api(sendRequest);
You can also find fully example here:
Full Email object Java example

How to send an email from an ASP.NET MVC view page with an attachment?

I have to send an email from my ASP.NET MVC 2 contact form view page.I need a detail answer that describes how to create the model , the controller and the view for that purpose .. Here is the code i have given in my controller class's action method..
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SendEMail(CareersEMailModel careersEMailModel,HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
bool isOK = false;
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("no-reply#abc.com", "Website contact form");
msg.To.Add("info#abc.com");
msg.Subject = "Resume";
string body = "Name:" + careersEMailModel.Name + "\n" + "Phone:" + careersEMailModel.Phone + "\n" + "Email:" + careersEMailModel.Email;
string file = careersEMailModel.Resume;
msg.Body = body;
msg.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient("mailserver_url.net", 25);
smtp.Send(msg);
msg.Dispose();
isOK = true;
CareersMessageModel rcpt = new CareersMessageModel();
rcpt.Title = "Email sent successfully!!";
rcpt.Content = "Your details has been received with great thanks.We'll contact you as soon as possible.";
return View("CareersMessage", rcpt);
}
catch (Exception ex)
{
CareersMessageModel err = new CareersMessageModel();
err.Title = "Sorry,Email sending failed!!!";
err.Content = "The website is having an error with sending this mail at this time.You can send an email to our address provided in our contact us form.Thank you.";
return View("CareersMessage", err);
}
}
else
{
return View();
}
}
For retrieving the uploaded file, you will need to do this
foreach (string file in Request.Files)
{
var uploadFile = Request.Files[file];
if (uploadFile.ContentLength == 0) continue;
string fileLocation = //File Location with file name, needs to be stored for temporary purpose
uploadFile.SaveAs(fileLocation);
}
Then with help of following code you can attach file
Attachment data = new Attachment(fileLocation, MediaTypeNames.Application.Octet);
message.Attachments.Add(data);
Once done with the email delete the file created on server.
Hope this answers your question
from MSDN
public static void CreateMessageWithAttachment(string server)
{
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
"ben#contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
ex.ToString() );
}
// Display the values in the ContentDisposition for the attachment.
ContentDisposition cd = data.ContentDisposition;
Console.WriteLine("Content disposition");
Console.WriteLine(cd.ToString());
Console.WriteLine("File {0}", cd.FileName);
Console.WriteLine("Size {0}", cd.Size);
Console.WriteLine("Creation {0}", cd.CreationDate);
Console.WriteLine("Modification {0}", cd.ModificationDate);
Console.WriteLine("Read {0}", cd.ReadDate);
Console.WriteLine("Inline {0}", cd.Inline);
Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
foreach (DictionaryEntry d in cd.Parameters)
{
Console.WriteLine("{0} = {1}", d.Key, d.Value);
}
data.Dispose();
}
EDIT:
the Attachment class accepts a stream. So try this. (i haven't tested it but it should give you the gist of what you need to do)
foreach (string fileName in Request.Files)
{
HttpPostedFile file = Request.Files[fileName];
Attachment data = new Attachment(file.InputStream, fileName);
// do stuff to attach it to the Mail Message
}

Sending mail in blackberry

i want to create an application which can send a email in blackberry. can i have a sample code or tutorial
thanks alot
U can send Email two types using API Directly or Programatically
public void sendemail(String s){
Message m = new Message();
Address a = null;
try
{
a = new Address("","");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Address[] addresses = {a};
try
{
m.addRecipients(net.rim.blackberry.api.mail.Message.RecipientType.TO, addresses);
m.setContent(s);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.setSubject(" My Croxley ");
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(m));
}
And Another this way
public boolean SendEmail(String emailFrom, String emailTo, String subject, String messageData, String fileName, byte[] fileData)
{
// create a multipart message
Multipart mp = new Multipart();
TextBodyPart tbp = new TextBodyPart(mp, messageData);
mp.addBodyPart(tbp);
SupportedAttachmentPart sap = new SupportedAttachmentPart(mp, "audio/amr", fileName, fileData);
mp.addBodyPart(sap);
// create a message in the sent items folder
Folder folders[] = Session.getDefaultInstance().getStore().list(Folder.SENT);
Message message = new Message(folders[0]);
// add recipients to the message and send
try
{
Address toAdd = new Address(emailTo, emailTo);
Address toAdds[] = new Address[1];
toAdds[0] = toAdd;
message.addRecipients(Message.RecipientType.TO, toAdds);
message.setSubject(subject);
message.setContent(mp);
//sets priority
//message.setPriority(Message.Priority.HIGH);
net.rim.blackberry.api.mail.Transport.send(message);
return true;
}
catch (Exception e)
{
return false;
}
}
Ypu can get started with this: http://www.blackberry.com/developers/docs/6.0.0api/Messaging-summary.html#MG_1