ในบทช่วยสอนง่ายๆ นี้ เราจะสำรวจวิธี ส่ง Email โดยใช้ Java SMTP เป็นหนึ่งในไคลเอนต์อีเมลยอดนิยม และคุณจะได้เรียนรู้วิธี ส่งอีเมลโดยใช้ SMTP ของ Gmail ใน Java แอปพลิเคชันใช้ประโยชน์จากการเรียก API อย่างง่ายที่สามารถใช้ในสภาพแวดล้อม Java ภายในระบบปฏิบัติการ Windows และ Linux
ขั้นตอนในการส่งอีเมลโดยใช้ Java
- กำหนดค่าแอปพลิเคชันโดยเพิ่มการอ้างอิงไฟล์ Aspose.Email JAR จาก Maven Repository
- สร้างอินสแตนซ์ MailMessage class เพื่อส่งอีเมล
- ตั้งค่าคุณสมบัติต่าง ๆ ของข้อความเมลที่ต้องการ
- ตั้งค่าคุณสมบัติ SmtpClient และส่งข้อความอีเมล
SMTP เป็นหนึ่งในไคลเอนต์อีเมลที่ง่ายที่สุดสำหรับการส่งและรับอีเมล ในตัวอย่างต่อไปนี้ เราใช้ MailMessage Class เพื่อสร้างข้อความที่จะส่ง ซึ่งเกี่ยวข้องกับการตั้งค่าหัวเรื่องอีเมล ผู้รับ และเนื้อหาอีเมล จากนั้นเราจะเริ่มต้นวัตถุ SmtpClient โดยเราจะตั้งค่าข้อมูลรับรองสำหรับผู้ใช้พร้อมกับข้อมูลพอร์ตและโฮสต์ สุดท้ายเราจะส่งข้อความอีเมลที่เราสร้างในขั้นตอนแรก ตัวอย่างต่อไปนี้เป็นการนำวิธี ส่ง Mail โดยใช้เซิร์ฟเวอร์ SMTP ในภาษา Java ไปใช้อย่างง่าย
รหัสเพื่อส่งอีเมลโดยใช้ Java
package testemail; | |
import com.aspose.email.License; | |
import com.aspose.email.MailAddressCollection; | |
import com.aspose.email.MailMessage; | |
import com.aspose.email.SecurityOptions; | |
import com.aspose.email.SmtpClient; | |
public class EmailKB { | |
public static void main(String[] emailArguments) { | |
// Apply the Aspose.Email license before sending email through Gmail SMTP | |
License emailLicense = new License(); | |
emailLicense.setLicense("EmailLicense.lic"); | |
// Create MailMessage instance to send email | |
MailMessage testEmailMessage = new MailMessage(); | |
// Set properties of desired mail message | |
testEmailMessage.setSubject("How to Send Mail Using SMTP Server in Java"); | |
// Adding the destination email address or addresses | |
MailAddressCollection mailAddresses = new MailAddressCollection(); | |
mailAddresses.add("TestReceiverEmail@EmailServer.com"); | |
testEmailMessage.setTo(mailAddresses); | |
testEmailMessage.setBody ("This is a test for sending email using SMTP using Java."); | |
// Create SmtpClient class object to send email | |
SmtpClient emailClient = new SmtpClient(); | |
// Setting the SmtpClient properties to set the credentials, host and port | |
emailClient.setHost("smtp.gmail.com"); | |
emailClient.setUsername("YourSourceEmail@gmail.com"); | |
emailClient.setPassword("Your Password for Gamil"); | |
emailClient.setPort(587); | |
emailClient.setSecurityOptions(SecurityOptions.SSLExplicit); | |
// Initiate the email message using Gmail's SMTP client | |
emailClient.send(testEmailMessage); | |
} | |
} |
ในหัวข้อที่แล้ว เรามุ่งเน้นไปที่ตัวอย่างการแสดงผลและสำรวจ วิธีเรนเดอร์ LaTeX เป็น PNG โดยใช้ Java หัวข้อนี้มุ่งเน้นที่การใช้ Java SMTP เพื่อส่งอีเมล โดยใช้วิธีการง่ายๆ