making newsletter(HTML) with SpringFramework3 - html

I am sending newsletter like below with Springframework 3.
private void sendMail(Map<String,Object> mailInfo) throws Exception{
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.myhost.com");
mailSender.setPort(587);
mailSender.setUsername("email#email.com");
mailSender.setPassword("12345");
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper mHelper = new MimeMessageHelper(msg, true, "UTF-8");
mHelper.setFrom(new InternetAddress(
mailInfo.get("send_mail").toString(), mailInfo.get("send_name").toString()));
mHelper.setTo(new InternetAddress(
mailInfo.get("recv_mail").toString(), mailInfo.get("recv_name").toString()));
mHelper.setText(mailInfo.get("mail_desc").toString(), true);
mHelper.setSubject(mailInfo.get("mail_title").toString());
mailSender.send(msg);
}
In my case value of mail_desc is an HTML(it has css and other resources). Mail goes well, but its CSS and all of images are broken.
I appended to all of src value like below in JSP
function getDomain(){
var DNS = location.href;
DNS = DNS.split('//');
DNS = 'http://' + DNS[1].substr(0,DNS[1].indexOf("/"));
return DNS;
}
So When I print this in browser console it returns localhost:8080/myApp/{image_src}.
However, When I open with gmail it looks quite different. it looks like...
<img src="https://ci5.googleusercontent.com/proxy/FVJ1IBTWmX0l0KPlNQVY_AkDsCL02O2Y_kZS7KACQlnXgfgNvNQvjBKpn9zIdPH84N_r-ulunXvzlMCVUOWsMG1WCjfYUFVX7VpjJ5OV5RdpV2ReZFjM9Yw=s0-d-e1-ft#http://localhost:8080/resources/gtl_portal/images/newsletter/ci.png" alt="ci" class="CToWUd">
Now I got questions like below :
How to implement newsletter in Normal? Where can I find some examples or references?(I think this can solve lots of problem here)
How to change value things looks like. it is quite tricky, since it is embedded in style attribute.:
<td height="50px" style="background:url('/resources/images/newsletter/top_bg.png') repeat-x 0 0;padding:15px">
Thanks a lot :D bb

You cant include your external css like you do normally , but you can prefer the way of wrapping the styles in the inline way (in <head> tag). So something like this,
<style>
.bigFont{
font-size:14px;
}
<style>
<body>
<p class='bigFont' >Hi , i am bigger </p>
</body>
so this looks separate instead adding style attribute to your tags , you can also avoid some code by resusing .
AFAIK , for adding inline images Spring framework has very good documentation. It is supported widely by mail clients, an example,
FileSystemResource res = new FileSystemResource(new File("c:/Sample.jpg"));
helper.addInline("identifier1234", res);
so that you can simply use it as <img src='cid:identifier1234'>.
For advanced templating options you can integrate your web app with Apache velocity, a templating library

Related

Cannot embed images in email with MailKit

This questions has been posed and answered several places on SO, specifically here : Issue with Gmail - Embedded images using MailKit
and handles my exact query, yet the answer doesn't seem to work for my case.
I've tried to build a simple mailer that embeds images in an HTML email, yet in several clients, all images still end up as attachments.
I suspect the fault to be in the way I handle the image attachments (one .gif and several .png) to be:
// Add pictures to embedded resources and replace links to pictures in the message
foreach (string imgpath in ImgPaths)
{
var image = builder.LinkedResources.Add(imgpath);
image.ContentId = MimeUtils.GenerateMessageId();
image.ContentDisposition = new ContentDisposition() { Disposition = ContentDisposition.Inline };
HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
}
builder.HtmlBody = HtmlFormat;
message.Body = builder.ToMessageBody();
I can see from the emails (received in Gmail, for instance), do show that the images are being listed as:
src="images/cid:TPSXHQUDSAU4.JJRKUIEGLTZ5#Loralei"
All images are attached as attachments in both clients I've tried (gmail and roundcube). I've walked through your tutorials and checked out everything here: https://stackoverflow.com/search?q=Mailkit+Embed
Sadly, I just can't seem to find my error. Hopefully #jstedfast could see where I make my mistake?
UPDATE
As mentioned by #jstedfast, the corrected code should be (for my case anyway):
foreach (string imgpath in ImgPaths)
{
var test = Path.GetFileName(imgpath);
var image = builder.LinkedResources.Add(imgpath);
image.ContentId = MimeUtils.GenerateMessageId();
image.ContentDisposition = new ContentDisposition() { Disposition = ContentDisposition.Inline };
//HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
HtmlFormat = HtmlFormat.Replace($"images/{test}", string.Format("cid:{0}", image.ContentId)); //use images/filename
}
This is a great guide to follow too, https://programming.vip/docs/5dac3983f0cd5.html
This looks like the problem:
<img src="images/cid:TPSXHQUDSAU4.JJRKUIEGLTZ5#Loralei" .../>
That needs to be:
<img src="cid:TPSXHQUDSAU4.JJRKUIEGLTZ5#Loralei" .../>
My guess is that in order to fix this, you'd change the following line of code:
HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
to this:
HtmlFormat = HtmlFormat.Replace(imgpath, string.Format("cid:{0}", image.ContentId));
Hope that helps!

How to get all of the headlines from a google news search using Jsoup

public static void main(String[] args) throws IOException {
Document doc = Jsoup.connect("https://www.google.com/search?q=tesla&oq=tesla&aqs=chrome.0.69i59l3j0l3.494j0j9&sourceid=chrome&ie=UTF-8#q=tesla&tbm=nws").userAgent("Mozilla").get();
Elements links = doc.select("div[class=_cnc]");
for (Element link : links) {
Elements titles = link.select("h3.r_U6c");
String title = titles.text();
System.out.println(title);
System.out.println("Headline: " + link.text());
System.out.println("Link: " + link.attr("data-href"));
}
}}
Here is the HTMl layout. I want to extract the titles for each of the links. I am just not sure on how to format the CSS selector portions of my code. I tried to look through some old threads but couldn't get anything to work. I am just looking for the text of the headlines not the actual links. The print link statements were just for some testing that I couldn't get running.
Thanks guys
Picture of HTML
The page you're trying to fetch is loaded with Javascript. Jsoup don't process Javascript scripts.
Instead use some tools like Selenium or ui4j.

Grails: displaying created image in gsp

I'm very new to Grails so there's probably a very simple answer to this question. I'm trying to display a dynamically created image in a gsp. The image is NOT stored in a database, it's created on the fly in the controller.
What I essentially have is one gsp that has a form which takes in a set of user inputs (requestGraph.gsp). Upon submitting the form, the parameters are sent to the a displayGraph action in the controller which queries information from a database completely outside of Grails and creates a chart using the JFreeChart library. I would like to display this image within a displayGraph.gsp or something like that.
So basically within requestGraph.gsp I have a snippet similar to:
<g:form action="displayGraph">
<!-- ... bunch of labels and boxes -->
<g:submitButton name="displayGraph" value="Display Graph" />
</g:form>
Within the controller I have something like:
def requestGraph = {}
def displayGraph = {
//... code that uses params to make an image byte array and assigns to var img
return [image : img]
}
Within displayGraph.gsp:
<body>
<h1>Graph Title</h1>
<!-- ??? How to dislpay image? -->
</body>
I tried piping the image directly to the output stream in the displayGraph action. This works, but then I lose control of all page formatting in displayGraph.gsp.
Most tutorials I've found create a dedicated action to pipe the image to an output steam then call that action using a tag. The problem is that my image isn't stored in a database and I see no way of passing the image byte array (or even the form parameters) to create/render the image. Can anybody help me with this? Thanks.
If you write the bytes to the output stream, you can treat the controller/action as the source of the image in your GSP. Here's a quick, untested example:
// controller action
def displayGraph = {
def img // byte array
//...
response.setHeader('Content-length', img.length)
response.contentType = 'image/png' // or the appropriate image content type
response.outputStream << img
response.outputStream.flush()
}
You could then access your image in the src of an <img> tag like this:
<img src="${createLink(controller: 'myController', action: 'displayGraph')}"/>
Update:
After reading your question again, this may or may not work - it looks like you might be displaying the graph as the result of a form submission. This will only work if you're storing the state on the server somewhere (instead of just getting it from the one request where the form is submitted). If you do store enough state on the server to generate the graph, then you'd have to provide some additional parameters to your controller to get the correct image, e.g. src="${g.link(controller: 'myController', action: 'displayGraph', params: ['id': 1234])}", where id is how you retrieve the graph state.
The following code works in Grails 2.x.
HomeController.groovy
class HomeController {
def index() {
}
def viewImage(){
def file = new File(params.title)
def img = file.bytes
response.contentType = 'image/png' // or the appropriate image content type
response.outputStream << img
response.outputStream.flush()
}
}
views/home/index.jsp
<%# page contentType="text/html;charset=ISO-8859-1" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<meta name="layout" content="main"/>
<title>View Image</title>
</head>
<body>
<div class="body">
<img src="<g:createLink controller="home" action="viewImage"
params="[title: 'C:/pictures/myimage.png']"/>"/>
</div>
</body>
</html>
I believe it's not about Grails but about HTML. You could:
Make the dedicated action that pipes image accept certain parameters, and generate the image in that action;
Embed it base64-encoded into HTML, like here:
<img src="data:image/gif;base64,R0lGODlhUAAPAKIAAAsL...etc..." alt="wow" />
my suggestion actually has two parts.
1) Use the solution recommend by Rob above to generate the chart artifact, however save it to a static file with a unique identifier that is passed back as part of the response from the form submit, then rendering the chart is no different then rendering any other image.
i would suggest that the identifer be constructed from the specifif params passed in on the form submit so they can be used as a caching mechanism to render the chart again without rebuilding it
2) create a service, maybe a Quartz Service, that periodically cleans up the static charts that were created for the application
Just an improvement to #Rob's answer:
Another option which is a bit nicer, you can just render the image, straight from your controller's action:
// controller action
def displayGraph = {
def img // a byte[], File or InputStream
render(file: img, contentType: 'image/png')
}
See also: http://grails.org/doc/latest/ref/Controllers/render.html
For any reasons the above solutions does not display any image. I used:
<img src='${createLink(controller: "myController", action: "displayGraph")}' />
instead.
I used FileUploadService to save the Image file In Grails .If you getting images from directory means, try this:
<img style="height: 120px;width: 102px;"src="${resource(dir:'personImages', file: personalDetailsInstance.id + '.png')}" />
Your gsp:
<img src="${createLink(controller: "image", action: "draw")}" />
Your controller:
def draw() {
byte[] imageInBytes = imageService.getImageInBytes() //should return byte array
response.with{
setHeader('Content-length', imageInBytes.length.toString())
contentType = 'image/jpg' // or the appropriate image content type
outputStream << imageInBytes
outputStream.flush()
}
}

How to display code in plain text?

I want to display bare code on an HTML page, I tried this:
<script>
function getSize() {
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
}
</script>
The above JavaScript code is some code entered by the user. I can't figure out to show this bare code on the html page without being interpreted and screwed up by the browser.
How do I display bare code on an HTML page?
I'm not quite clear on the specifics of the issue, as pre tags should, in general, do the trick, but here's an alternative tag:
<xmp>[Code can be displayed here]</xmp>
If you're using a server-side language, though, I'd suggest converting to HTML entities before outputting, then using CSS to style it.
As well, be sure if you're accepting user input that any JavaScript is being filtered and never executed.
You can use the <pre> and <code> tags to display formatted code. But to prevent the code from executing and not displaying you'll need to convert the text to character entities. > becomes >, < becomes &lt, etc.
You could do this by using PHP, for example:
<?php echo htmlentities('function getSize() { var myFSO = new
ActiveXObject("Scripting.FileSystemObject");
var filepath =
document.upload.file.value; var
thefile = myFSO.getFile(filepath);
var size = thefile.size; alert(size
+ " bytes"); }'); ?>
As your system relies on user input, you might have to rely on AJAX to actually process the user input and convert it to HTML entities.
Use the <code></code> tag, and use javascript or your sever-side scripting language
Dump it into a textarea and render it like a div tag
This is a bit of a hack and parlor trick, but it works.
Get bare code rendered onto an HTML page is to place it in a text area and remove all the formatting around the textarea so it looks like a <div> tag:
Code:<br>
<textarea style="border: none;width:400;height:200;background-color:lightgrey;">
#include<iostream>
using namespace std;
class Box{
public:
int mymethod(){ cout << "is method"; }
};
int myfunction(){ cout << "is function"; }
int main(){
Box b;
b.mymethod();
myfunction();
}
</textarea>
<br>
Output:
<pre>is methodis function
</pre>
The above html code should render like this on the page:
What I've done is invalid HTML, it only works because customary error handling happens to handle it this way. You shouldn't put unescaped angle brackets in the content of a <textarea>. You get undefined behavior depending on how the browser chooses to interpret your textarea tag.
The most reliable method is to htmlencode the code to be displayed on the page.
For example
< into &lt
space into &nbsp
etc.

Sending values through links

Here is the situation: I have 2 pages.
What I want is to have a number of text links(<a href="">) on page 1 all directing to page 2, but I want each link to send a different value.
On page 2 I want to show that value like this:
Hello you clicked {value}
Another point to take into account is that I can't use any php in this situation, just html.
Can you use any scripting? Something like Javascript. If you can, then pass the values along in the query string (just add a "?ValueName=Value") to the end of your links. Then on the target page retrieve the query string value. The following site shows how to parse it out: Parsing the Query String.
Here's the Javascript code you would need:
var qs = new Querystring();
var v1 = qs.get("ValueName")
From there you should be able to work with the passed value.
Javascript can get it. Say, you're trying to get the querystring value from this url: http://foo.com/default.html?foo=bar
var tabvalue = getQueryVariable("foo");
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++)
{
var pair = vars[i].split("=");
if (pair[0] == variable)
{
return pair[1];
}
}
}
** Not 100% certain if my JS code here is correct, as I didn't test it.
You might be able to accomplish this using HTML Anchors.
http://www.w3schools.com/HTML/html_links.asp
Append your data to the HREF tag of your links ad use javascript on second page to parse the URL and display wathever you want
http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript
It's not clean, but it should work.
Use document.location.search and split()
http://www.example.com/example.html?argument=value
var queryString = document.location.search();
var parts = queryString.split('=');
document.write(parts[0]); // The argument name
document.write(parts[1]); // The value
Hope it helps
Well this is pretty basic with javascript, but if you want more of this and more advanced stuff you should really look into php for instance. Using php it's easy to get variables from one page to another, here's an example:
the url:
localhost/index.php?myvar=Hello World
You can then access myvar in index.php using this bit of code:
$myvar =$_GET['myvar'];
Ok thanks for all your replies, i'll take a look if i can find a way to use the scripts.
It's really annoying since i have to work around a CMS, because in the CMS, all pages are created with a Wysiwyg editor which tend to filter out unrecognized tags/scripts.
Edit: Ok it seems that the damn wysiwyg editor only recognizes html tags... (as expected)
Using php
<?
$passthis = "See you on the other side";
echo '<form action="whereyouwantittogo.php" target="_blank" method="post">'.
'<input type="text" name="passthis1" value="'.
$passthis .' " /> '.
'<button type="Submit" value="Submit" >Submit</button>'.
'</form>';
?>
The script for the page you would like to pass the info to:
<?
$thispassed = $_POST['passthis1'];
echo '<textarea>'. $thispassed .'</textarea>';
echo $thispassed;
?>
Use this two codes on seperate pages with the latter at whereyouwantittogo.php and you should be in business.