Javamail Read Body of Message Until EOF - email

The following code is supposed to send and save messages sent via yahoomail. The sending part works OK but id does not save the sent message. I've been researching and found the following code:
/**
* Read the body of the message until EOF.
*/
public static String collect(BufferedReader in) throws IOException {
String line;
StringBuffer sb = new StringBuffer();
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
return sb.toString();
}
How do I incorporate it in the following code?
public void doSendYahooMail(){
from = txtFrom.getText();
password= new String(txtPassword.getPassword());
to = txtTo.getText();
cc = txtCC.getText();
bcc = txtBCC.getText();
subject = txtSubject.getText();
message_body = jtaMessage.getText();
//String imapHost = "imap.mail.yahoo.com";
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.mail.yahoo.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.imap.host", "imap.mail.yahoo.com");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.port", "993");
Session session = Session.getInstance(props,null);
try {
// message definition
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
if(!cc.equals("")){
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
}
if(!bcc.equals("")){
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
}
message.setSubject(subject);
if(!filename.equals("")){// if a file has been attached...
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(message_body);// actual message
Multipart multipart = new MimeMultipart();// create multipart message
// set the text message part
multipart.addBodyPart(messageBodyPart);//add the text message to the multipart
// attachment part
messageBodyPart = new MimeBodyPart();
String attachment = fileAbsolutePath;
DataSource source = new FileDataSource(attachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);//add the attachment to the multipart message
// combine text and attachment
message.setContent(multipart);
// send the complete message
Transport.send(message, from, password);
}
else{// if no file has been attached
message.setText(message_body);
Transport.send(message, from, password);
}
JOptionPane.showMessageDialog(this, "Message Sent!","Sent",JOptionPane.INFORMATION_MESSAGE);
filename = "";//reset filename to null after message is sent
fileAbsolutePath = "";//reset absolute path name to null after message is sent
// save sent message
Store store = session.getStore("imap");
store.connect(from, password);
Folder folder = store.getFolder("Sent");
if(!folder.exists()){
folder.create(Folder.HOLDS_MESSAGES);
Message[] msg = new Message[1];
msg[0] = message;
folder.appendMessages(msg);
}
store.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}

Related

Error in sending mail : java.net.SocketException: Connection reset

I am trying to send mail with attachment with dynamic recepients but getting the following error :
I am able to ping the host though.
Following is the stack trace
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2460)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2187)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
Below is the code snippet :
protected void Sendmail(String opt,String val)
{
String LogFile = "QAS.log";
String sender = "xyz.com";
String host = "smtp.xyz.com";
Properties prop = System.getProperties();
prop.put("mail.smtp.host", host);
Session session = Session.getDefaultInstance(prop);
try
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(LogFile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("Process_Log");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(Mail_Notify.substring(0,Mail_Notify.length()-1)));
Transport.send(message);
System.out.println("Mail successfully sent");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}

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;
}

Asynchronous email notification in groovy

I have the below code in a groovy class, I want to call this method asynchronously from various other groovy classes.
public void sendNotification(){
//async true
String from = ApplicationConfig.email_From;
String sendTo = ApplicationConfig.email_To;
String host = ApplicationConfig.email_Host;
String subject = ApplicationConfig.email_Subject;
String textToSend = ApplicationConfig.email_Text;
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(sendTo));
message.setSubject(subject);
message.setText(textToSend);
Transport.send(message);
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
So far I couldn't find anything that fits my requirement, there are some plugins in grails, but I'm not using grails.
Just use an ExecutorService
ExecutorService pool = Executors.newFixedThreadPool(2)
def sender = { ->
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", ApplicationConfig.email_Host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(ApplicationConfig.email_From));
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(ApplicationConfig.email_To));
message.setSubject(ApplicationConfig.email_Subject);
message.setText(ApplicationConfig.email_Text);
Transport.send(message);
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
public void sendNotification() {
pool.submit(sender)
}

Send a file from server to client in GWT

I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}

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
}