How do I write an email body to a text file using the Java Gmail API - email

i'm trying to access my Gmail account using Java Gmail API then access the body of the first Email and then save it into text file using this path in my computer D:\Email , so any suggestion ? i have tried so many examples such as using saveFile but none of them worked for me !
NOTE: i want only to save the body of the Email
package ReadingEmail;
import java.util.*;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
//===================================================================================
public class ReadingEmail {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
System.out.println("enter your email");
String email= input.nextLine();
System.out.println("enter your password");
String pass= input.nextLine();
store.connect("imap.gmail.com", email, pass); //connect to email
Folder inbox = store.getFolder("INBOX");// go to index
inbox.open(Folder.READ_ONLY); // open index
//==============================================================================================
int messageCount = inbox.getMessageCount();// line 20,21 show the number of emails
System.out.println("Total Messages" + messageCount);
int Message1 = messageCount;
int Message2 = Message1 -1 ;
Message msg1= inbox.getMessage(messageCount);
Message msg2= inbox.getMessage(Message2);
Address[] in1 = msg1.getFrom();
for (Address address1 : in1) {}
//================================================================================
Message msg = inbox.getMessage(inbox.getMessageCount());
Address[] in = msg.getFrom();
for (Address address : in) {
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("CONTENT:" + bp.getContent());
}
catch (Exception ex) // wrong password
{ System.out.println("the email or password is wrong "); }
}
}

Are you getting any error? Right now I am unable to see any code to save to a file.
Also when you use System.out.println("CONTENT:" + bp.getContent()); are you able to print the text to console or not?

Related

How to fetch unread email using javax.mail pop3 from outlook

I am trying to fetch unread email from Inbox(Outlook.office365.com) and also copy the read message to another folder. But I am getting some of the following issues.
Email is being re-read again, even if we mark the email as being
read programmatically.
Unable to copy an email to another folder even when we open the Inbox is RW(Read&Write) mode.
Attached my code as well.
package com.xyz.mail;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FlagTerm;
public class ReadEmail {
private static final String TRUE = "true";
private static final String MAIL_POP3_HOST = "mail.pop3.host";
private static final String MAIL_POP3_PORT = "mail.pop3.port";
private static final String MAIL_POP3_STARTTLS_ENABLE = "mail.pop3.starttls.enable";
private static final String MAIL_FOLDER_INBOX = "INBOX";
public static void check(String host, String storeType, String user, String password) throws Exception {
Store store = null;
Folder emailFolder = null;
try {
Properties properties = new Properties();
properties.put(MAIL_POP3_HOST, host);
properties.put(MAIL_POP3_PORT, "995");
properties.put(MAIL_POP3_STARTTLS_ENABLE, TRUE);
Session emailSession = Session.getDefaultInstance(properties);
// create the POP3 store object and connect with the pop server
store = emailSession.getStore(storeType);
store.connect(host, user, password);
emailFolder = store.getFolder(MAIL_FOLDER_INBOX);
emailFolder.open(Folder.READ_WRITE);
Message[] messages = emailFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
System.out.println("messages.length---" + messages.length);
if (messages.length == 0) {
System.out.println("No new messages found.");
} else {
for (int i = 0, len = messages.length; i < len; i++) {
Message message = messages[i];
boolean hasAttachments = hasAttachments(message);
if (hasAttachments) {
System.out.println(
"Email #" + (i + 1) + " with subject " + message.getSubject() + " has attachments.");
readAttachment(message);
} else {
System.out.println("Email #" + (i + 1) + " with subject " + message.getSubject()
+ " does not have any attachments.");
continue;
}
Folder copyFolder = store.getFolder("copyData");
if (copyFolder.exists()) {
System.out.println("copy messages...");
copyFolder.copyMessages(messages, emailFolder);
message.setFlag(Flags.Flag.DELETED, true);
}
}
}
} catch (Exception e) {
throw new Exception(e);
} finally {
emailFolder.close(false);
store.close();
}
}
public static void main(String[] args) throws Exception {
String host = "outlook.office365.com";
String username = "emailtest#xyz.com";
String password = "passw0rd{}";
String mailStoreType = "pop3s";
check(host, mailStoreType, username, password);
}
private static boolean hasAttachments(Message msg) throws Exception {
if (msg.isMimeType("multipart/mixed")) {
Multipart mp = (Multipart) msg.getContent();
if (mp.getCount() > 1) {
return true;
}
}
return false;
}
public static void readAttachment(Message message) throws Exception {
Multipart multiPart = (Multipart) message.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
String destFilePath = "/home/user/Documents/" + part.getFileName();
System.out.println("Email attachement ---- " + destFilePath);
FileOutputStream output = new FileOutputStream(destFilePath);
InputStream input = part.getInputStream();
byte[] buffer = new byte[4096];
int byteRead;
while ((byteRead = input.read(buffer)) != -1) {
output.write(buffer, 0, byteRead);
}
output.close();
}
}
}
}
How to I fetch only unread email and copy the email to another folder.
change the protocal to imap and change the prot respecitvely ..using pop3 we can access only inbox that is the reason why you are unable to copy the mail to another folder

Autodiscover cannot process the given e-mail address. Only mailboxes and contacts are allowed

While sending email using ExchangeService is throwing Exception as Message is: "The Autodiscover service returned an error." and "Autodiscover cannot process the given e-mail address.
Only mailboxes and contacts are allowed".
public void SendEmail(string to, string cc, string subject, string body, string emailType)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.Credentials = new WebCredentials("test#outlook.com", "test");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("test#outlook.com", RedirectionUrlValidationCallback);
EmailMessage email = new EmailMessage(service);
email.ToRecipients.Add(to);
email.CcRecipients.Add(cc);
email.Subject = subject;
email.Body = new MessageBody(body);
email.Send();
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
if (redirectionUri.Scheme == "https")
{
result = true;
}
return true;
}
the above code is working fine with "...#microsoft.com" but not working with "...outlook.com"
can anyone help to resolve issue.

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

jnetpcap get html web page source code

I'm using jnetpcap to analyzing packet. I want to get html web page source code.
However, when I use html.page() to get source code I get some messy code which look like binary code. Can anyone help me? How to solve it?
Not a jnetpcap expert, but I have been using this class for a while and it seems to work. It actually gets many HTTP fields, including its payload.
package br.com.mvalle.ids.sniffer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapIf;
import org.jnetpcap.packet.PcapPacket;
import org.jnetpcap.packet.PcapPacketHandler;
import org.jnetpcap.packet.format.FormatUtils;
import org.jnetpcap.protocol.network.Ip4;
import org.jnetpcap.protocol.tcpip.Http;
import org.jnetpcap.protocol.tcpip.Tcp;
public class Sniffer {
private List<PcapIf> alldevs = new ArrayList<PcapIf>(); // Will be filled with NICs
private StringBuilder errbuf = new StringBuilder(); // For any error msgs
private PcapIf selectedDevice;
private Pcap pcap;
private PcapPacketHandler<String> jpacketHandler;
public Sniffer(){
listDevices();
selectedDevice = selectDevice(1);
openDevice(selectedDevice);
packetHandler();
capturePackets();
}
public void listDevices(){
int r = Pcap.findAllDevs(alldevs, errbuf);
if (r == Pcap.NOT_OK || alldevs.isEmpty()) {
System.err.printf("Can't read list of devices, error is %s", errbuf.toString());
return;
}
System.out.println("Network devices found:");
int i = 0;
for (PcapIf device : alldevs) {
String description =
(device.getDescription() != null) ? device.getDescription()
: "No description available";
System.out.printf("#%d: %s [%s]\n", i++, device.getName(), description);
}
}
private PcapIf selectDevice(int deviceId){
PcapIf device = alldevs.get(1); // We know we have atleast 1 device (parameter changed from 0 to 1)
System.out
.printf("\nChoosing '%s' on your behalf:\n",
(device.getDescription() != null) ? device.getDescription()
: device.getName());
return device;
}
private void openDevice (PcapIf device){
int snaplen = 64 * 1024; // Capture all packets, no trucation
int flags = Pcap.MODE_PROMISCUOUS; // capture all packets
int timeout = 10 * 1000; // 10 seconds in millis
pcap =
Pcap.openLive(device.getName(), snaplen, flags, timeout, errbuf);
if (pcap == null) {
System.err.printf("Error while opening device for capture: "
+ errbuf.toString());
return;
}
}
private void packetHandler(){
jpacketHandler = new PcapPacketHandler<String>() {
Http httpheader = new Http();
public void nextPacket(PcapPacket packet, String user) {
if(packet.hasHeader(httpheader)){
System.out.println(httpheader.toString());
if(httpheader.hasPayload()){
System.out.println("HTTP payload: (string length is "
+new String(httpheader.getPayload()).length()+")");
System.out.println(new String(httpheader.getPayload()));
System.out.println("HTTP truncated? "
+httpheader.isPayloadTruncated());
}
//System.out.println(packet.toString());
}}
};
}
private void capturePackets(){
pcap.loop(pcap.LOOP_INFINITE , jpacketHandler, "Received Packet");
pcap.close();
}
}
Hope it helps.

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
}