package
com.barcode.demo; import
java.awt.Color; import
java.awt.Font; import
java.awt.GradientPaint; import
java.awt.Graphics2D; import
java.awt.image.BufferedImage; import
java.io.File; import
java.io.IOException; import
java.sql.Timestamp; import
java.util.Properties; import
javax.activation.DataHandler; import
javax.activation.DataSource; import
javax.activation.FileDataSource; import
javax.imageio.ImageIO; import
javax.mail.BodyPart; import
javax.mail.Message; import
javax.mail.PasswordAuthentication; import
javax.mail.Session; import
javax.mail.Transport; import
javax.mail.internet.InternetAddress; import
javax.mail.internet.MimeBodyPart; import
javax.mail.internet.MimeMessage; import
javax.mail.internet.MimeMultipart; public class
CreateCaptchaImage { public static void main(String[] args) { customCaptchaGeneration (); } /** * Default constructor. * * @param title *
the frame title. */ public static void customCaptchaGeneration()
{ File file = null; Timestamp timestamp = new
Timestamp(System.currentTimeMillis()); try { file = File .createTempFile(timestamp.getTime() +
"_Captcha", ".png"); } catch (IOException e) { e.printStackTrace(); } StringBuffer sb = createHtmlData(); sendEmailToRecepint(file, sb); } private static StringBuffer createHtmlData()
{ StringBuffer sb = new StringBuffer();
sb.append("<html><head></head><body><table><tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th></tr><tr>"); sb.append("<td rowspan="); sb.append(10); sb.append('"'); sb.append(" colspan="); sb.append(3); sb.append('"'); sb.append('>'); sb.append("<img src="); sb.append("'"); sb.append("cid:ea-image"); sb.append("'"); sb.append("width="); sb.append('"'); sb.append(200); sb.append('"'); sb.append("height="); sb.append('"'); sb.append(200); sb.append('"'); sb.append('/'); sb.append('>');
sb.append("</td><th></th><th></th><th></th></tr></body></html>"); return sb; /** * <td rowspan="10"
colspan="3"> * <img src='cid:ea-image' * style="display: block; margin-left:
auto; margin-right: auto;" * width="200"
height="200"/></td> */ } private static void sendEmailToRecepint(File
file, StringBuffer sb) { // Recipient's email ID needs to be
mentioned. String to = "kmandal@gmail.com"; // Sender's email ID needs to be mentioned String from =
"kmandal@kmical.com"; final String username =
"kmandal";// change accordingly final String password =
"XXXXXXXXXXXXXXXX";// change accordingly // Assuming you are sending email through
relay.jangosmtp.net String host =
"XXXXXXXXXXXXXXXXXX"; Properties props = new Properties(); props.put("mail.smtp.auth",
"true");
props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host",
host); props.put("mail.smtp.port",
"25"); Session session =
Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication
getPasswordAuthentication() { return new
PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new
MimeMessage(session); // Set From: header field of the header. message.setFrom(new
InternetAddress(from)); // Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Demo
snapshot"); MimeMultipart multipart = new
MimeMultipart(); BodyPart messageBodyPart = new
MimeBodyPart(); messageBodyPart.setContent(sb.toString(),
"text/HTML"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); createCaptchaImage(file); DataSource fds = new FileDataSource(file); messageBodyPart.setDataHandler(new
DataHandler(fds)); // ea-image is image file name
messageBodyPart.setHeader("Content-ID",
"<ea-image>"); // add image to the multipart multipart.addBodyPart(messageBodyPart); // put everything together message.setContent(multipart); Transport.send(message); } catch (Exception e) { System.out.println("Error of
file"); } } public static void createCaptchaImage(File
file) { Timestamp timestamp = new
Timestamp(System.currentTimeMillis()); BufferedImage image = new
BufferedImage(200, 40, BufferedImage.TYPE_BYTE_INDEXED); Graphics2D graphics =
image.createGraphics(); // Set back ground of the generated image
to white graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, 200, 40); // set gradient font of text to be
converted to image GradientPaint gradientPaint = new
GradientPaint(10, 5, Color.BLUE, 20, 10, Color.LIGHT_GRAY, true); graphics.setPaint(gradientPaint); Font font = new Font("Comic Sans
MS", Font.BOLD, 30); graphics.setFont(font); // write 'Hello World!' string in the image
graphics.drawString(String.valueOf(timestamp.getTime()), 5, 30); // release resources used by graphics
context graphics.dispose(); try { ImageIO.write(image, "png",
file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
The provided code generates a CAPTCHA image, embeds it into
an email, and sends it as an attachment. Below is a step-by-step explanation of
how this program works:
1. Generating the CAPTCHA Image
The program generates a simple image with the current
timestamp. The createCaptchaImage function creates a BufferedImage and uses Graphics2D
to write text (timestamp) on the image. This image is later saved as a PNG
file.
2. Email Setup
The program uses JavaMail API to send an email. It
configures SMTP properties (like host, port, and authentication), constructs a MimeMessage,
and embeds the CAPTCHA image as an inline attachment. The image is referenced
using Content-ID in the email body as cid:ea-image.
How the program works:
- cutomCaptchaGeneration():
Ø
This is the main function that starts the
process.
Ø
A temporary file is created to store the
generated CAPTCHA image.
Ø
HTML data with the image placeholder is created
via createHtmlData().
Ø
The email is sent with the generated CAPTCHA
image using sendEmailToRecepint().
- createHtmlData():
Ø
Generates the HTML content with an image
placeholder (cid:ea-image). This is the inline image reference used to embed
the CAPTCHA image.
- sendEmailToRecepint(File
file, StringBuffer sb):
Ø
Sets up email properties and authentication
details.
Ø
Composes the email body by adding the HTML
content and embedding the image file.
Ø
The image is attached to the email and
referenced using the Content-ID (<ea-image>).
Ø
The email is sent using Transport.send().
- createCaptchaImage(File
file):
Ø
Creates the CAPTCHA image by generating a simple
timestamp image.
Ø
A gradient font effect is applied to the text.
Code Review and Suggestions:
- Sensitive
Information:
Ø
Ensure that sensitive information like email
username, password, and host are stored securely, such as in environment
variables or a configuration file, rather than hardcoding them in the source
code.
- SMTP
Settings:
Ø
Replace the placeholders in SMTP configuration (host,
username, password) with valid credentials.
- Exception
Handling:
Ø
Improve the exception handling in sendEmailToRecepint()
method by logging detailed errors instead of just printing "Error of
file".
- Temporary
File Handling:
Ø
The temporary file is created using File.createTempFile(),
which is good for ensuring a unique filename, but it is also important to
delete these temporary files after they are used.
Suggested Improvements:
- Better
CAPTCHA Design:
Ø
Add random alphanumeric strings and distortions
(e.g., lines, dots) to the CAPTCHA image to improve security and randomness.
- HTML
Email Template:
Ø
The HTML email structure could be further
enhanced with CSS for better styling and responsiveness.
Conclusion:
This is a basic implementation of a CAPTCHA generator and
email sender. It demonstrates how to integrate image generation and sending the
image inline within an HTML email using JavaMail. To make it production-ready,
consider security improvements, better error handling, and enhanced CAPTCHA
image generation.
Create dynamic text image like as captcha |
0 Comments