Universal Acceptance (UA) Micro-Learning Module: Module 9- Programming in Email Address Internationalization(EAI) Using Java.
Instructor Guide
1st Edition.
���© 2024 Creative Commons License - Attribution 4.0 International (CC BY 4.0).�
Universal Acceptance
Programming in EAI Using Java, UA Micro-Learning Module Objectives:
| 2
Note About the Utilization of Unicode String Literals :
| 3
EAI programming: Handling Non-ASCII Characters in Emails:
| 4
EAI Programming: Handling Subject and Header Lines with UTF-8/Non-ASCII Characters:�
Example1: MIME Encoded-Word Syntax Representing the Arabic Word “Marhaba”:
In the example above:
=?UTF-8?Q?مرحبا?=
| 5
EAI Programming: Handling Subject and Header Lines with UTF-8/Non-ASCII Characters:�
| 6
Example: Code Snippet for Handling Subject Line with UTF-8/non-ASCII Characters in Java:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
public class SubjectLine {
public static void main(String[] args) {
// Define sender and recipient email addresses
String sender_email = 'your_sender_email@example.com' # Replace with your sender's email address
String recipient_email = 'recipient_email@example.com' # Replace with the recipient's email address
// Set the subject line with non-ASCII characters
| 7
Example: Code Snippet for Handling Subject Line with UTF-8/non-ASCII Characters in Java:
String subject = "Subject with Non-ASCII Characters: 你好, Hello";
// Create a MIME message
MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
try {
// Set the From address
message.setFrom(new InternetAddress(senderEmail));
// Set the To address
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
// Set the subject line
message.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
// Continue building and sending the email...
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
| 8
EAI Programming: Handling Email Body with UTF-8/Non-ASCII Characters: �
message.setHeader("Content-Type", "text/plain; charset=utf-8");
String emailBody = "你好, Hello";
byte[] encodedBody = emailBody.getBytes(StandardCharsets.UTF_8);
| 9
EAI Programming: Handling Email Body with UTF-8/Non-ASCII Characters: �
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(encodedBody, "text/plain; charset=utf-8");
message.addBodyPart(bodyPart);
Transport.send(message);
| 10
EAI Programming: Full Java Code for Handling Subject Line, Header Line and Email Body with UTF-8/Non-ASCII Characters (1/3):
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
public class EAIExample {
public static void main(String[] args) {
// Define sender and recipient email addresses
sender_email = 'your_sender_email@example.com' # Replace with your sender's email address
recipient_email = 'recipient_email@example.com' # Replace with the recipient's email address
// Create a Properties object to hold the SMTP server details
Properties props = new Properties();
props.put("mail.smtp.host", "your_smtp_server.com"); // Replace with your SMTP server address
props.put("mail.smtp.port", "587"); // Replace with the appropriate port
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
| 11
EAI Programming: Full Java Code for Handling Subject Line, Header Line and Email Body with UTF-8/Non-ASCII Characters (2/3):
// Create a Session object with the provided properties and authentication
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_smtp_username",
"your_smtp_password");
}
});
try {
// Create a new MimeMessage object
MimeMessage message = new MimeMessage(session);
// Set the sender, recipient, and subject of the email
message.setFrom(new InternetAddress(senderEmail));
message.setRecipient(Message.RecipientType.TO,
new InternetAddress(recipientEmail));
message.setSubject("Internationalized Email Body Text");
// Create a new MimeBodyPart object and set the content of the email
MimeBodyPart bodyPart = new MimeBodyPart();
| 12
EAI Programming: Full Java Code for Handling Subject Line, Header Line and Email Body with UTF-8/Non-ASCII Characters (3/3):
String messageText = "Hello,\n\n"
+ "This is an example of internationalized email body text. It includes non-ASCII
characters like مرحبًا,ሀሎ,ආයුබෝවන්, 你好
(Arabic, Ethiopic, Sinhala and Chinese for \"Hello\").\n"
+ "Feel free to add more internationalized content as you like.\n\n"
+ "Best regards,\n"
+ "Your Name\n";
bodyPart.setText(messageText, "utf-8");
// Create a Multipart object and add the MimeBodyPart to it
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart);
// Set the content of the message to the Multipart object
message.setContent(multipart);
// Send the email
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (Exception e) {
System.out.println("Email sending failed: " + e.getMessage());}
}}
| 13
EAI Programming: Handling Attachments with UTF-8/Non-ASCII Characters:
| 14
Example: Code Snippets for Parts of the Java code for Handling Attachments in UTF-8:
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
# Defining Email Configuration
sender_email = 'تجربة-بريد-الكتروني@تجربة-القبول-الشامل.موريتانيا'
recipient_email = '电子邮件测试@普遍适用测试.我爱你'
message = MIMEMultipart()
| 15
Example: Code Snippets for Parts of the Java code for Handling Attachments in UTF-8: Composing Email Content:
// Composing Email Content
message.setFrom(new InternetAddress(sender_email));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient_email));
message.setSubject("Email with Attachment");
String message_text = "Hello,\n\n" +
"Please find the attached file.\n\n" +
"Best regards,\n" +
"Your Name\n";
messageBodyPart.setText(message_text);
multipart.addBodyPart(messageBodyPart);
String attachment_file = "path/to/attachment";
File attachment = new File(attachment_file);
DataSource source = new FileDataSource(attachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachment.getName());
multipart.addBodyPart(messageBodyPart);
| 16
Example: Code Snippets for Parts of the Java code for Handling Attachments in UTF-8: Sending Email with Attachment(1/2):
String smtp_server = "your_smtp_server.com";
int smtp_port = 587;
String smtp_username = "your_smtp_username";
String smtp_password = "your_smtp_password";
// Create a Properties object to store mail server configuration
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtp_server);
props.put("mail.smtp.port", smtp_port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Create a Session object with authentication
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtp_username, smtp_password);
}
});
| 17
Example: Code Snippets for Parts of the Java code for Handling Attachments in UTF-8: Sending Email with Attachment(2/2):
try {
// Connect to the SMTP server
Transport transport = session.getTransport("smtp");
transport.connect(smtp_server, smtp_port, smtp_username, smtp_password);
// Send the email message
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
| 18
Example: Full Code for Handling Attachments with UTF-8/Non-ASCII Characters in Java(1/4):
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
public class EmailWithAttachmentExample {
public static void main(String[] args) {
// Define sender and recipient email addresses
String senderEmail = "تجربة-بريد-الكتروني@تجربة-القبول-الشامل.موريتانيا"; // Replace with your sender's email address
String recipientEmail = "电子邮件测试@普遍适用测试.我爱你"; // Replace with recipient's email address
// Create a Properties object to hold the SMTP server details
Properties props = new Properties();
| 19
Example: Full Code for Handling Attachments with UTF-8/Non-ASCII Characters in Java(2/4):
props.put("mail.smtp.host", "your_smtp_server.com"); // Replace with your SMTP server address
props.put("mail.smtp.port", "587"); // Replace with the appropriate port
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Create a Session object with the provided properties and authentication
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_smtp_username", "your_smtp_password"); // Replace with your SMTP username and password
}
});
try {
// Create a new MimeMessage object
MimeMessage message = new MimeMessage(session);
// Set the sender, recipient, and subject of the email
message.setFrom(new InternetAddress(senderEmail));
| 20
Example: Full Code for Handling Attachments with UTF-8/Non-ASCII Characters in Java(3/4):
message.setRecipient(Message.RecipientType.TO,new InternetAddress(recipientEmail));
message.setSubject("Email with Attachment");
// Create a new MimeBodyPart object for the email text
MimeBodyPart textPart = new MimeBodyPart();
String messageText = "Hello,\n\n"
+ "Please find the attached file.\n\n"
+ "Best regards,\n"
+ "Your Name\n";
textPart.setText(messageText, "utf-8");
// Create a new MimeBodyPart object for the attachment
MimeBodyPart attachmentPart = new MimeBodyPart();
File attachmentFile = new File("path/to/attachment"); // Replace with the path to your attachment file
FileDataSource dataSource = new FileDataSource(attachmentFile);
attachmentPart.setDataHandler(new DataHandler(dataSource));
attachmentPart.setFileName(MimeUtility.encodeText(dataSource.getName(), "utf-8", null));
| 21
Example: Full Code for Handling Attachments with UTF-8/Non-ASCII Characters in Java(4/4):
// Create a Multipart object and add the MimeBodyParts to it
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(textPart);
multipart.addBodyPart(attachmentPart);
// Set the content of the message to the Multipart object
message.setContent(multipart);
// Send the email
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (Exception e) {
System.out.println("Email sending failed: " + e.getMessage());
}
}
| 22
Example: Handling Attachments with UTF-8/Non-ASCII Filename in Java(1/2):
import javax.activation.*;
import javax.mail.internet.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class AttachmentNonASCII {
public static void main(String[] args) {
String attachmentFilename = "文件名.pdf"; // Non-ASCII filename
MimeBodyPart attachment = handleAttachment(attachmentFilename);
}
public static MimeBodyPart handleAttachment(String filename) {
MimeBodyPart attachment = new MimeBodyPart();
try {
// Encode the filename using UTF-8
String encodedFilename = MimeUtility.encodeText(filename, StandardCharsets.UTF_8.name(), null);
| 23
Example: Handling Attachments with UTF-8/Non-ASCII Filename in Java(2/2):
// Set the Content-Disposition header with the encoded filename
String contentDisposition = String.format("attachment; filename=\"%s\"", encodedFilename);
// Create the email attachment object
DataSource source = new FileDataSource(filename);
attachment.setDataHandler(new DataHandler(source));
// Set the Content-Disposition header for the attachment
attachment.setHeader("Content-Disposition", contentDisposition);
// Encode the attachment as base64
attachment.setDisposition(MimeBodyPart.ATTACHMENT);
return attachment;
} catch (MessagingException | UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
| 24
Handling SMTP Interactions with EAI Support: Libraries and APIs�
| 25
Example: Sending Emails with EAI Address with Java’s JavaMails(1/3):
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
String senderEmail = "تجربة-بريد-الكتروني@example.com";
String recipientEmail = "电子邮件测试@example.com";
// Create the email message
String messageContent = "مرحبًا,ሀሎ,ආයුබෝවන්";
String subject = "Multilingual Email";
}
| 26
Example: Sending Emails with EAI Address with Java’s JavaMails(2/3):
try {
// Set SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", "your_smtp_server.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// Create a Session object
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your_smtp_username", "your_smtp_password");
}
});
| 27
Example: Sending Emails with EAI Address with Java’s JavaMails(3/3):
// Create the email message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmail));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
message.setSubject(subject);
message.setText(messageContent, "utf-8");
// Send the email
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
| 28
Ensuring Email Delivery Across Languages: Internationalized Email Address Validation with Confirmation Links:
| 29
Ensuring Email Delivery Across Languages: Internationalized Email Address Validation with Confirmation Links(1/7):
String user_email = "你好@example.com";
String confirmation_token = "unique_token_generated_for_user";
| 30
Ensuring Email Delivery Across Languages: Internationalized Email Address Validation with Confirmation Links(2/7):
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSender {
public static void main(String[] args) {
// Email configuration
String smtpServer = "your_smtp_server.com";
int smtpPort = 587;
String smtpUsername = "your_smtp_username";
String smtpPassword = "your_smtp_password";
// Sender and recipient details
String fromEmail = "noreply@example.com";
String toEmail = "user@example.com"; // Replace with the recipient's email address
// Email content
String confirmationToken = "unique_token_generated_for_user";
String emailSubject = "Confirm Your Email Address";
| 31
Ensuring Email Delivery Across Languages: Internationalized Email Address Validation with Confirmation Links(3/7):
String emailBody = "Click the following link to confirm your email address:
http://example.com/confirm?token=" + confirmationToken;
// Email properties
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.port", smtpPort);
// Create session with authentication
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtpUsername, smtpPassword);
}
});
| 32
Ensuring Email Delivery Across Languages: Internationalized Email Address Validation with Confirmation Links(4/7):
try {
// Create email message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
message.setSubject(emailSubject);
message.setText(emailBody);
// Send email
Transport.send(message);
System.out.println("Email sent successfully!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
| 33
Ensuring Email Delivery Across Languages: Internationalized Email Address Validation with Confirmation Links(5/7):
String clicked_token = "unique_token_generated_for_user";
String user_email = "user@example.com";
// Verify the clicked token against the stored token
String stored_token = database.get(user_email);
Map<String, String> database = new HashMap<>();
// Store the user_email and confirmation_token in the database
database.put(user_email, confirmation_token);
| 34
Ensuring Email Delivery Across Languages: Internationalized Email Address Validation with Confirmation Links(6/7):
if (clicked_token.equals(stored_token)) {
System.out.println("Email address confirmed.");
} else {
System.out.println("Confirmation link is invalid.");
}
}
// Sample database storing confirmation tokens associated with email addresses
static Map<String, String> database = new HashMap<>();
static {
// Populating sample data (replace with actual data)
database.put("user@example.com", "unique_token_generated_for_user");
}
| 35
Ensuring Email Delivery Across Languages: Internationalized Email Address Validation with Confirmation Links(7/7):
| 36
Understanding Multilingual Mailboxes: Parsing Internationalized Email Addresses:
| 37
Example: Validating Email Addresses Length(1/2):
import java.util.regex.*;
public class EmailAddressLengthValidation {
public static void main(String[] args) {
// Test email validation
String email = "تجربة-بريد-الكتروني@تجربة-القبول-الشامل.موريتاني";
boolean isValid = isValidEmailAddress(email);
System.out.println("Is valid email address: " + isValid);
}
public static boolean isValidEmailAddress(String email) {
try {
// Validate email address using regular expression
String pattern = "^[\\w\\.-]+@[\\w\\.-]+\\.\\w+$";
Pattern emailPattern = Pattern.compile(pattern);
Matcher matcher = emailPattern.matcher(email);
| 38
Example: Validating Email Addresses Length(2/2):
if (!matcher.matches()) {
return false;
}
// Check length validation
String[] parts = email.split("@");
return email.length() <= 254 && parts[0].length() <= 64 && parts[1].length() <= 255;
} catch (Exception e) {
return false;
}
}
}
Output:
Is valid email address: True
| 39
EAI-Specific Considerations for Setting Up Email Mailbox Names:
| 40
Reference:
[1].Freed, N., & Borenstein, N. (1996). Multipurpose Internet Mail Extensions (MIME) Part 3: Message Header Extensions for Non-ASCII Text (RFC 2047). Retrieved from [https://www.ietf.org/] on 2023-12-11.
[2]. Klensin, J., & Hildebrand, M. (2008). Internationalized Email Headers (RFC 5335). Retrieved from [https://datatracker.ietf.org/wg/tewg/documents/] on 2023-12-11.
[3]. The Unicode Consortium. (n.d.). Retrieved from https://unicode.org/consortium/] on 2023-12-11.
[4]. Freed, N. (1996). Multipurpose Internet Mail Extensions (MIME) Part 5: Base64 Content-Transfer-Encoding (RFC 2048). Retrieved from http://tools.ietf.org/html/rfc2048: http://tools.ietf.org/html/rfc2048 on 2023-12-11.
[5]. Python, Chardet. (n.d.). Retrieved from https://github.com/chardet/chardet on 2023-12-11.
[6]. Python, Idna. (n.d.). Retrieved from https://pypi.org/project/idna/
[7]. Java, Java Platform, Standard Edition 7 API Specification. (n.d.). Charset class. Retrieved from https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html on 2023-12-11..
[8]. Hoffman, P., & Dürst, M. (2010, July). Internationalized Domain Names in Applications (IDNA2008) (RFC 5893). Retrieved from https://www.ietf.org/ on on 2023-12-11.
[9]. Python Documentation, (n.d.):https://docs.python.org/: https://docs.python.org/, on 2023-12-11.
| 41
Reference:
[10]. JavaMail, (nd): https://www.oracle.com/java/technologies/javamail-api.html, on 2023-12-11.
[11]. Python, smtplib module, (n.d.): https://docs.python.org/3/library/smtplib.html, on 2023-12-11.
[12]. (Stack Exchange, 2023). What's the best approach to confirm user email address - sending an email-confirm link? Retrieved from https://ux.stackexchange.com/questions/111252/from-a-ux-perspective-when-should-you-send-the-confirm-your-email-message on December 11, 2023.
| 42
Author:
| 43