---
# System prepended metadata

title: Email Sample Code
tags: [java, email, sample code, code]

---

```java 
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

public class MailTest {

    public static void main(String[] args) {

    	String username = ""; //填入 gmail 帳號

        //寄信密碼，如果使用 gmail 寄信的話要去申請 google app password
        //https://www.getmailbird.com/gmail-app-password/
    	String password = "";    

    	String host = "smtp.gmail.com"; //郵件伺服器
        String port = "587";	        //寄件的埠號, port

        String subject = "郵件主題";
        String content = "<div style='color: red'>123456</div><br>";
        content += "<H1>Hello</H1><img src=\"cid:mytestcid\">";

        // 寄件人和收件人設定
        String fromEmail = "";  //同 username 即可
        String toEmail = "";    //填入收件者 mail 位置

        // 建立郵件內容
        Properties properties = System.getProperties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        
        Session session = 
            Session.getDefaultInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            Message message = new MimeMessage(session);
            
            //TODO 的地方改寫成希望對方 mail 顯示的收件者名稱
            message.setFrom(new InternetAddress(fromEmail, "TODO"));

            message.setRecipients(
                Message.RecipientType.TO, InternetAddress.parse(toEmail));
            message.setSubject(subject);
            MimeMultipart multipart = new MimeMultipart("related");
            BodyPart messageBodyPart = new MimeBodyPart();
            
            //加上 charset=UTF-8 中文字體才會顯示正確編碼
            messageBodyPart.setContent(content, "text/html;charset=UTF-8");
            multipart.addBodyPart(messageBodyPart);

            // second part (the image)
            messageBodyPart = new MimeBodyPart();

            //TODO 改成圖片完整檔案路徑跟檔名
            DataSource fds = new FileDataSource("TODO");
            
            messageBodyPart.setDataHandler(new DataHandler(fds));

            //mytestcid 這個字串
            //要跟 content 內 cid: 後方的 mytestcid 一致，不限定字串內容
            messageBodyPart.setHeader("Content-ID", "<mytestcid>");
            
            // add image to the multipart
            multipart.addBodyPart(messageBodyPart);

            //附加檔案
            MimeBodyPart filePart = new MimeBodyPart();
            //TODO 改成完整檔案路徑跟檔名
            FileDataSource fileDataSource = new FileDataSource("TODO");
            filePart.setDataHandler(new DataHandler(fileDataSource));
            filePart.setFileName(fileDataSource.getName());
            multipart.addBodyPart(filePart);

            // put everything together
            message.setContent(multipart);
            // Send message
            Transport.send(message);

            System.out.println("郵件已成功寄出。");
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

```