Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Properties;
- import javax.mail.Authenticator;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- public class Email {
- public static void main(String[] args) throws MessagingException {
- String host = "smtp.gmail.com";
- int port = 465;
- final String username = "jason19951003@gmail.com";//smtp帳號
- final String password = "***";//smtp密碼
- Properties props = new Properties();
- props.put("mail.smtp.host", host);
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.socketFactory.port", "465");
- props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
- props.put("mail.smtp.port", port);
- Session session = Session.getInstance(props, new Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(username, password);
- }
- });
- Message message = new MimeMessage(session);
- message.setFrom(new InternetAddress("jason19951003@gmail.com"));//設定寄件人帳號
- message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("b19951003@gmail.com"));//設定收件人帳號
- message.setSubject("測試HTML寄信.");//設定主旨
- //message.setText("test");//寄送純文字
- message.setContent("<h1>This is a test</h1>", "text/html; charset=utf-8");//寄送html格式的email
- Transport transport = session.getTransport("smtp");
- transport.connect(host, port, username, password);
- Transport.send(message);
- transport.close();
- System.out.println("寄送email結束.");
- }
- }
Add Comment
Please, Sign In to add comment