I need to send a mail with attachment in java using sendgrid api. I am mentioning files like [filename.xls]=bytearray. I am getting this byte array using jxl api. I am able to send the mail ,but xls is not having the values.
Code :
sendgridUrl+"?api_user="+apiUser + "&api_key=" + apiPassword + ""
+ to + "&subject=" + (subject.replaceAll(" ", "%20")) + "&fromname="
+ senderPersonal + "&files[" + fileName + "]=" + value2
+ "&html=" + message + "&from=" + AppConfig.getProperty("senderemail");
private static bool SendMailUsingSendgrid(EmailSendRequestDTO request)
{
try
{
string htmlContent = string.Empty;
string plainTextContent = string.Empty;
// Set apikey
var apiKey = ConfigReader.Read(CommonEnums.ConfigKeys.SendgridApiKey);
// Initialize sendgrid client.
var client = new SendGridClient(apiKey);
// From address
var from = new EmailAddress(request.FromAddress, request.FromDisplayName);
// Subject
var subject = request.Subject;
// Send mail to multiple recepients.
var recepientList = new List<EmailAddress>();
if (!string.IsNullOrEmpty(request.ToAddresses))
{
foreach (var toAddress in request.ToAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
recepientList.Add(new EmailAddress(toAddress));
}
}
// If content in html format
if (request.IsHtmlFormat)
{
htmlContent = request.Body;
}
else
{
plainTextContent = request.Body;
}
// Creat object to send mail message.
var mailMessage = MailHelper.CreateSingleEmailToMultipleRecipients(from, recepientList, subject, plainTextContent, htmlContent);
// add multiple cc.
var ccList = new List<EmailAddress>();
if (!string.IsNullOrEmpty(request.CCAddresses))
{
foreach (var ccAddress in request.CCAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
ccList.Add(new EmailAddress(ccAddress));
}
}
// add multiple bcc.
var bccList = new List<EmailAddress>();
if (!string.IsNullOrEmpty(request.BCCAddresses))
{
foreach (var bccAddress in request.BCCAddresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
bccList.Add(new EmailAddress(bccAddress));
}
}
// Attachments
if (!string.IsNullOrEmpty(request.AttachmentFile))
{
foreach (var attachmentFile in request.AttachmentFile.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
SendGrid.Helpers.Mail.Attachment messageAttachment = new SendGrid.Helpers.Mail.Attachment();
mailMessage.Attachments.Add(messageAttachment);
}
}
var response = client.SendEmailAsync(mailMessage).Result;
return true;
}
catch (Exception)
{
return false;
}
}
Related
I want to read the mail inbox and gather scheduled events. I could do it by reading .ics file the attachment. Outlook can do calendar scheduling and add another attachment to that. In that special case, I could not read .ics file as an attachment. But there is a Part as multipart/alternative. I could not get it as a readable one.
public EmailContentDTO WriteAndReadCalendarFiles(Message message) {
try {
LOGGER.info("Start function WriteAndReadCalendarFiles");
// create calendar entry
Map<String, String> calendarEntry = null;
// get as multipart object
Object content = emailFolder.getMessage(message.getMessageNumber()).getContent();
Multipart multipart = (Multipart) content;
Address[] recipients = message.getAllRecipients();
LOGGER.info("multipart.getCount() : " + multipart.getCount());
// get multipart one by one
for (int k = 0; k < multipart.getCount(); k++) {
// write ICS file
Part part = multipart.getBodyPart(k);
// LOGGER.info("Attachment properties: Disposition:" + part.getDisposition()+", Description: "+ part.getDescription()+" Content-Type: "+part.getContentType() + "File name:" + part.getFileName());
if ((part.getFileName() != null && part.getFileName().endsWith(".ics")) || part.getContentType().contains("text/calendar;")) {
// LOGGER.debug("File name:" + part.getFileName());
String disposition = part.getDisposition();
if (disposition == null) disposition = "attachment";
String fileUploadDir = environment.getRequiredProperty("icsFileUploadDirectory");
//make directory
File uploadDirectory = new File(fileUploadDir);
if (!uploadDirectory.exists()) {
uploadDirectory.mkdirs();
}
String fileName = "invite.ics";
if (disposition.contains("attachment")) {
LOGGER.info("start write ics file");
writeICSFile("invite.ics", fileUploadDir, part.getInputStream());
}
// read ICS file
FileInputStream fileInputStream = new FileInputStream(fileUploadDir + fileName);
// create calendar object
CalendarBuilder builder = new CalendarBuilder();
Calendar calendar = builder.build(fileInputStream);
// read calender object and retrieve data
for (Iterator i = calendar.getComponents().iterator(); i.hasNext(); ) {
Component component = (Component) i.next();
if (component.getName().equalsIgnoreCase("VEVENT")) {
calendarEntry = new HashMap<>();
for (Iterator j = component.getProperties().iterator(); j.hasNext(); ) {
net.fortuna.ical4j.model.Property property = (Property) j.next();
calendarEntry.put(property.getName(), property.getValue());
//get time zome
if (property.getName().equals("DTSTART")) {
Parameter tzid = property.getParameter("TZID");
if (tzid != null) {
calendarEntry.put("TZID", tzid.getValue());
}
}
}
// get ATTENDEES
ArrayList<String> attendees = new ArrayList<>();
//format address to tags email format and add to the list
for (Address address : recipients) {
String nonFormatAddress = address.toString();
if (nonFormatAddress.contains("<")) {
Pattern pattern = Pattern.compile("<(.*?)>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(nonFormatAddress);
if (matcher.find()) {
attendees.add(matcher.group(1));
}
} else {
attendees.add(address.toString());
}
}
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
Date startTime = dateFormat.parse(calendarEntry.get("DTSTART").split("z")[0]);
Date endTime = dateFormat.parse(calendarEntry.get("DTEND").split("z")[0]);
if (calendarEntry.containsKey("TZID")) {
if (calendarEntry.get("TZID").toLowerCase().contains("sri lanka")) {
startTime = dateGenerator.changeHoursOfDate(startTime, -330);
endTime = dateGenerator.changeHoursOfDate(endTime, -330);
}
}
// Create EmailContentDTO object
EmailContentDTO emailContentDTO = new EmailContentDTO(calendarEntry.get("SUMMARY"),
calendarEntry.get("ORGANIZER").split(":")[1],
calendarEntry.get("UID"), attendees,
(calendarEntry.get("LOCATION") != null) ? calendarEntry.get("LOCATION") : "",
(calendarEntry.get("DESCRIPTION") != null) ? calendarEntry.get("DESCRIPTION").split(":")[0] : "",
startTime, endTime, Integer.parseInt(calendarEntry.get("SEQUENCE")));
return emailContentDTO;
}
}
}
}
return null;
} catch (Exception e) {
LOGGER.error("Function WriteAndReadCalendarFiles : " + e.getMessage(), e);
e.printStackTrace();
return null;
}
}
Recently, I review the kafka code and test. I found a strange case:
I print the bytebuffer on the entry of SocketServer processCompletedReceives, as well as print the value on the point of Log sotre as follows:
the entry of SocketServer
private def processCompletedReceives() {
selector.completedReceives.asScala.foreach { receive =>
try {
openOrClosingChannel(receive.source) match {
case Some(channel) =>
val header = RequestHeader.parse(receive.payload)
val connectionId = receive.source
val context = new RequestContext(header, connectionId, channel.socketAddress,
channel.principal, listenerName, securityProtocol)
val req = new RequestChannel.Request(processor = id, context = context,
startTimeNanos = time.nanoseconds, memoryPool, receive.payload, requestChannel.metrics)
if(header.apiKey() == ApiKeys.PRODUCE){
LogHelper.log("produce request: %v" + java.util.Arrays.toString(receive.payload.array()))
}
...
the point of Log
validRecords.records().asScala.foreach { record =>
LogHelper.log("buffer info: value " + java.util.Arrays.toString(record.value().array()))
}
but, the result of print is different. and record.value() is not what I passed in client value like this:
public void run() {
int messageNo = 1;
while (true) {
String messageStr = "Message_" + messageNo;
long startTime = System.currentTimeMillis();
if (isAsync) { // Send asynchronously
producer.send(new ProducerRecord<>(topic,
messageNo,
messageStr), new DemoCallBack(startTime, messageNo, messageStr));
} else { // Send synchronously
try {
producer.send(new ProducerRecord<>(topic,
messageNo,
messageStr)).get();
System.out.println("Sent message: (" + messageNo + ", " + messageStr + ")");
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
++messageNo;
}
}
the print result is not the not String messageStr = "Message_" + messageNo;
so what happend in the case.
done. I write the code as follows:
public class KVExtractor {
private static final Logger logger = LoggerFactory.getLogger(KVExtractor.class);
public static Map.Entry<byte[], byte[]> extract(Record record) {
if (record.hasKey() && record.hasValue()) {
byte[] key = new byte[record.key().limit()];
record.key().get(key);
byte[] value = new byte[record.value().limit()];
record.value().get(value);
System.out.println("key : " + new String(key) + " value: " + new String(value));
return new AbstractMap.SimpleEntry<byte[], byte[]>(key, value);
}else if(record.hasValue()){
// illegal impl
byte[] data = new byte[record.value().limit()];
record.value().get(data);
System.out.println("no key but with value : " + new String(data));
}
return null;
}
}
This is my code to split URL, but that code have problem. All link appear with double word, example www.utem.edu.my/portal/portal . the words /portal/portal always double in any link appear. Any suggestion to me extract links in the webpage?
public String crawlURL(String strUrl) {
String results = ""; // For return
String protocol = "http://";
// Assigns the input to the inURL variable and checks to add http
String inURL = strUrl;
if (!inURL.toLowerCase().contains("http://".toLowerCase()) &&
!inURL.toLowerCase().contains("https://".toLowerCase())) {
inURL = protocol + inURL;
}
// Pulls URL contents from the web
String contectURL = pullURL(inURL);
if (contectURL == "") { // If it fails, then try with https
protocol = "https://";
inURL = protocol + inURL.split("http://")[1];
contectURL = pullURL(inURL);
}
// Declares some variables to be used inside loop
String aTagAttr = "";
String href = "";
String msg = "";
// Finds A tag and stores its href value into output var
String bodyTag = contectURL.split("<body")[1]; // Find 1st <body>
String[] aTags = bodyTag.split(">"); // Splits on every tag
//To show link different from one another
int index = 0;
for (String s: aTags) {
// Process only if it is A tag and contains href
if (s.toLowerCase().contains("<a") && s.toLowerCase().contains("href")) {
aTagAttr = s.split("href")[1]; // Split on href
// Split on space if it contains it
if (aTagAttr.toLowerCase().contains("\\s"))
aTagAttr = aTagAttr.split("\\s")[2];
// Splits on the link and deals with " or ' quotes
href = aTagAttr.split(((aTagAttr.toLowerCase().contains("\""))? "\"" : "\'"))[1];
if (!results.toLowerCase().contains(href))
//results += "~~~ " + href + "\r\n";
/*
* Last touches to URl before display
* Adds http(s):// if not exist
* Adds base url if not exist
*/
if(results.toLowerCase().indexOf("about") != -1) {
//Contains 'about'
}
if (!href.toLowerCase().contains("http://") && !href.toLowerCase().contains("https://")) {
// http:// + baseURL + href
if (!href.toLowerCase().contains(inURL.split("://")[1]))
href = protocol + inURL.split("://")[1] + href;
else
href = protocol + href;
}
System.out.println(href);//debug
consider to use the URL class...
Use it as suggested by the documentation :
)
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}
the output:
protocol = http
authority = example.com:80
host = example.com
port = 80
etc
after this you can take the elements you need an create a new one string/URL :)
I am calling a external process (git command) from inside of doPost method of my servlet. The post request comes to the servlet via an xhttpRequest() call when user clicks on a button.
In my code I am printing out the response HTML using the writer object of the response. And weirdly when the code reaches the process part it executes fine in the background but I don't see the correct response. Does someone has some insights to this problem? I am using streamgobbler class as described in this link: http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
Snippet of the process part of the code from the doPost() method is below.
try {
String line;
List<String> lines = new ArrayList<String>();
Process cloneProcess = Runtime.getRuntime().exec("git clone " +
hvafModifiedXMLRepository + " " +
xmlRepoPath.toString());
StreamGobbler errorGlobber = new StreamGobbler(cloneProcess.getErrorStream(), "CMDTOOL-E",resp.getWriter());
StreamGobbler outputGlobber = new StreamGobbler(cloneProcess.getInputStream(), "CMDTOOL-O",resp.getWriter());
errorGlobber.start();
outputGlobber.start();
cloneProcess.waitFor();
if (cloneProcess.exitValue() != 0)
throw new IOException(org.apache.commons.lang.StringUtils.join(lines, "\n"));
System.out.println("Done.");
} catch (IOException ex) {
sendLogHead(resp);
sendLog(resp, "Unable to clone Modified XML repository.", ex);
sendLogTail(resp);
return;
}
Here is my POST request.
function sendSelectedTestCasesToServlet(paramData, projName, uniqueInstanceName, configCapabilities) {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200)
document.getElementById('content').parentElement.removeChild(document.getElementById('content'));
document.getElementById('footer').parentElement.removeChild(document.getElementById('footer'));
var el = document.createElement('html');
el.innerHTML = xhttp.responseText;
var newBody = document.createElement('div');
newBody.innerHTML = AJS.$(el.getElementsByTagName('body')[0]).html();
document.body.appendChild(newBody);
window.stop();
}
else if (xhttp.readyState == 4 && xhttp.status == 404) {
return;
} else if (xhttp.readyState == 4 && xhttp.status == 500) {
document.getElementById('content').parentElement.removeChild(document.getElementById('content'));
document.getElementById('footer').parentElement.removeChild(document.getElementById('footer'));
var el = document.createElement('html');
el.innerHTML = xhttp.responseText;
var newBody = document.createElement('div');
newBody.innerHTML = AJS.$(el.getElementsByTagName('body')[0]).html();
document.body.appendChild(newBody);
window.stop();
}
};var baseurl = window.location.protocol + '//' + window.location.host + new URI(window.location.href).path()
xhttp.open('POST', baseurl + '?test-cases-for-configs=' + paramData + '&project-name=' + projName + '&job-instance-uniqueId=' + uniqueInstanceName + '&havf-config-capabilities=' + configCapabilities, true);
xhttp.send()
}
I'm writing a special permission forms program using MySQL, Javascript, and HTML code, which both respond to. I'm doing all of this using singleton pattern access and facade code(s) in java, and a services code, which responds to the singleton pattern codes.
I'm trying To retrieve a form (AKA 1 Result) by the variables, courseDept & courseNm.
This is a snippet of code I'm using to do all this:
FormDataFacade.java code snippet:
#Path("/specialPermissions/sp")
#GET
#Produces("text/plain")
public Response getSpecialPermissionFormByDeptAndRoomNm(#QueryParam("courseDept") String theDept, #QueryParam("courseNm") String theNm)
throws NamingException, SQLException, ClassNotFoundException
{
//Referenciation to FormDataFacade class.
FormDataFacade iFacade = FormDataFacade.getInstance();
int intNm = 0;
try {
intNm = Integer.parseInt(theNm);
}catch (NumberFormatException FAIL) {
intNm = 1;
}
//Aiming for forms with matching departments & room numbers by calling FormDataFacade
//method, getSpecialPermissionFormByDeptAndRoomNm.
SpecialPermissionForms[] orgaForm = iFacade.getSpecialPermissionFormByDeptAndRoomNm(theDept, intNm);
//Json String Representation...
if (orgaForm != null)
{
Gson neoArcadia = new Gson();
String result = neoArcadia.toJson(orgaForm);
//Json String added to response message body...
ResponseBuilder rb = Response.ok(result, MediaType.TEXT_PLAIN);
rb.status(200); //HTTP Status code has been set!
return rb.build(); //Creating & Returning Response.
}
else
{ //In case of finding no form data for the procedure...
return Response.status(700).build();
}
}
FormDataServices.java code snippet:
public SpecialPermissionForms[] getSpecialPermissionFormByDeptAndRoomNm(String theDept, int theNm) throws SQLException, ClassNotFoundException
{
Connection con = zeon.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT formID, studentName, courseDept, courseNm, semester, year, reasonCode FROM spforms WHERE courseDept = ? & courseNm = ?");
pstmt.setString(1, theDept);
pstmt.setInt(2, theNm);
ResultSet rs = pstmt.executeQuery();
SpecialPermissionForms[] neoForm = new SpecialPermissionForms[50];
int current = 0;
while (rs.next())
{
int formID3 = rs.getInt("formID");
String studentName3 = rs.getString("studentName");
String courseDept3 = rs.getString("courseDept");
String courseNm3 = rs.getString("courseNm");
String semester3 = rs.getString("semester");
int year3 = rs.getInt("year");
String reasonCode3 = rs.getString("reasonCode");
SpecialPermissionForms neo = new SpecialPermissionForms(formID3, studentName3, courseDept3, courseNm3, semester3, year3, reasonCode3);
neoForm[current] = neo;
current++;
}
if (current > 0)
{
neoForm = Arrays.copyOf(neoForm, current);
return neoForm;
}
else
{
return null;
}
}
Forms.html code snippet which both pieces of java code respond to:
$("#btnOneName").click(function() {
alert("clicked");
var inputId1=document.getElementById("t_specialFormCourseDept").value;
var inputId2=document.getElementById("t_specialFormCourseNm").value;
var theData = "courseDept=" + inputId1 + "&" + "courseNm=" + inputId2;
alert("Sending: " + theData);
var theUrl = "http://localhost:8080/onlineforms/services/enrollment/specialPermissions/sp?courseDept=&courseNm="+ theData;
$.ajax( {
url: theUrl,
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
var neoForm = JSON.parse(result);
alert(neoForm);
var output="<h3>Current Form Lists:</h3>";
output += "<ul>";
for (var current = 0; current < neoForm.length; current++)
{
output += "<li>" + neoForm[current].formID + ": " + neoForm[current].studentName + " (" + neoForm[current].courseDept + " - " + neoForm[current].courseNm + ") " +
" (" + neoForm[current].semester + " - " + neoForm[current].year + ") " + " - " + neoForm[current].reasonCode + "</li>";
}
output += "</ul>";
alert(output);
$("#p_retrieveOneName").html(output);
},
error:function(xhr) {
alert("error");
$("#p_retrieveOneName").html("Error:"+xhr.status+" "+xhr.statusText);}
} );
});
});
Now, when I go test this code in my webservice after successfully compiling it, it does work, however it retrieves everything, including the specific results I was searching for - I only want to return the results I have specifically searched for and nothing else. What exactly am I doing wrong here in these snippets of code?
Any suggestions or steps in the right direction are highly welcome.