반응형
Gmail 에서 JAVA 프로그래밍을 통한 이메일을 보내려면 계정설정에서 앱 비밀번호로 로그인 이 가능하도록 2단계 인증을 거쳐 16자리 새로운 암호를 할당받아야 한다.
Email Server 까지 만들기는 귀찮으니 많이들 사용하는 Gmail 계정을 JAVA 와 연결해서 메일을 보내는 법을 알아봅시다.
우선 를 다운 받거나 gradle 이나 maven dependency 에 추가시키자.
### build.gradle.kts
제 build.gradle.kts
파일은 다음과 같음. (Vert.x server 를 쓰기 때문에...)
```[.linenums.lang-kts]
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.api.tasks.testing.logging.TestLogEvent.*
plugins {
java
application
id("com.github.johnrengelman.shadow") version "8.1.1"
}
group = "net.recoeve"
version = "1.0.0-SNAPSHOT"
repositories {
mavenCentral()
}
val vertxVersion = "4.5.1"
val junitJupiterVersion = "5.9.1"
val mainVerticleName = "recoeve.http.MainVerticle"
val launcherClassName = "io.vertx.core.Launcher"
val watchForChange = "src/**/*"
val doOnChange = "${projectDir}/gradlew classes"
application {
mainClass.set(launcherClassName)
}
dependencies {
implementation("io.netty:netty-all:4.1.104.Final")
// https://mavenlibs.com/maven/dependency/mysql/mysql-connector-java
implementation("mysql:mysql-connector-java:8.0.33")
// https://mavenlibs.com/maven/dependency/com.mysql/mysql-connector-j
implementation("com.mysql:mysql-connector-j:8.1.0")
// https://mvnrepository.com/artifact/jakarta.mail/jakarta.mail-api
implementation("com.sun.mail:jakarta.mail:2.0.1")
implementation("org.jsoup:jsoup:1.17.1")
// https://mvnrepository.com/artifact/io.vertx/vertx-core
implementation("io.vertx:vertx-core:$vertxVersion")
//Thanks for using https://jar-download.com
implementation("io.micrometer:micrometer-registry-prometheus:1.12.1")
// https://mvnrepository.com/artifact/io.vertx/vertx-micrometer-metrics
implementation("io.vertx:vertx-micrometer-metrics:$vertxVersion")
implementation(platform("io.vertx:vertx-stack-depchain:$vertxVersion"))
implementation("io.vertx:vertx-web-client")
implementation("io.vertx:vertx-web")
implementation("io.vertx:vertx-web-openapi")
implementation("io.vertx:vertx-mysql-client")
implementation("io.vertx:vertx-http-service-factory")
implementation("io.vertx:vertx-json-schema")
implementation("io.vertx:vertx-web-api-contract")
implementation("io.vertx:vertx-rx-java3")
implementation("io.vertx:vertx-auth-oauth2:$vertxVersion")
implementation("io.vertx:vertx-jdbc-client")
implementation("io.vertx:vertx-config")
implementation("io.vertx:vertx-rx-java2")
implementation("io.vertx:vertx-rx-java")
implementation("io.vertx:vertx-mail-client")
implementation("io.vertx:vertx-auth-jdbc")
testImplementation("io.vertx:vertx-junit5")
testImplementation("org.junit.jupiter:junit-jupiter:$junitJupiterVersion")
implementation("org.seleniumhq.selenium:selenium-java:4.17.0") // https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
tasks.withType<ShadowJar> {
archiveClassifier.set("fat")
manifest {
attributes(mapOf("Main-Verticle" to mainVerticleName))
}
mergeServiceFiles()
}
tasks.withType<Test> {
useJUnitPlatform()
testLogging {
events = setOf(PASSED, SKIPPED, FAILED)
}
}
tasks.withType<JavaExec> {
args = listOf("run", mainVerticleName, "--redeploy=$watchForChange", "--launcher-class=$launcherClassName", "--on-redeploy=$doOnChange")
}
```/
```[.linenums]
gradlew build
gradlew run
// 과 같은 명령어로 java 파일 전체를 compile 하고 dependencies 를 자동으로 다운받고 할 수 있음.
```/
### JAVA code
그리고 아래와 같이 JAVA 코드를 작성하면 잘 돌아감. 해당 코드는 https://mailtrap.io/blog/jakarta-mail-tutorial/#Sending-HTML-email-in-Jakarta-Mail 에서 가져왔고, 제가 class 이름, 변수 등을 약간 수정함.
```[.scrollable.lang-java]
package recoeve.http;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import java.util.Properties;
public class Gmail {
private static final String username = "recoeve";
private static final String amho = "***amho***"; // 구글계정에서 2단계 인증을 거쳐 받은 16자리 앱 암호입력.
private static final Properties prop = new Properties();
static {
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
private static final Session session = Session.getInstance(
prop, new jakarta.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, amho);
}
});
/**
* Send email using Gmail SMTP server.
*
* @param recipientEmail TO recipient
* @param ccEmail CC recipient. Can be empty if there is no CC recipient
* @param title title of the message
* @param message message to be sent
* @throws MessagingException if the connection is dead or not in the connected
* state or if the message is not a MimeMessage
*/
public static void send(String recipientEmail, String ccEmail, String title, String message) {
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("recoeve@gmail.com"));
msg.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(recipientEmail));
msg.setSubject(title);
msg.setContent(message, "text/html; charset=utf-8");
Transport.send(msg);
} catch (MessagingException e) {
e.printStackTrace();
}
}
public static void main(String... args) throws Exception {
Gmail.send("kipid84@naver.com", "", "title", "<h1>HTML message.</h1>"); // 테스트.
}
}
```/
### "Not provider of jakarta.mail.util.StreamProvider was found" Error handle
최근까지 업데이트 되고 있는 https://mvnrepository.com/artifact/jakarta.mail/jakarta.mail-api/2.1.3 를 dependency 에 넣고 실행시켰더니 "Not provider of jakarta.mail.util.StreamProvider was found" 에러가 발생했었음. 뭔가가 업데이트 되면서 code 를 좀 바꿔줘야 하는것도 같은데... 방법을 찾기가 너무 어려워서 그냥 downgrade 시킨 버전으로 해결 봤음.
최신 버전 사용법을 알고 계신 분은 댓글로 좀 알려주세요.
## Email Server 만들기
아예 Email Server 까지 돌리면서 JAVA 랑 연결해서 자동화 시키는 방법도 있는거 같긴한데... 귀찮;;; 방법은 알아서 찾아보시길. 시간날때 정리하겠음; (아예 안할지도ㅋ)
## 네이버 메일 by 자바 (Naver mail by JavaMail) :: 너무 오래된 문서라 지금은 도움이 안될듯.
우선 에서 javax.mail.jar
file 을 다운받읍시다. 적당한 폴더에 넣어놓고, 이 폴더\javax.mail.jar
를 윈도우 변수(?) CLASSPATH
에 포함시킵시다. 아니면 java compile 하거나 실행시킬때, javac -classpath "folder path\javax.mail.jar;other classes"
, java -classpath "folder path\javax.mail.jar;other classes"
식으로 실행시키면 됨.
그리고 아래와 같이 JAVA 코드를 작성하면 잘 돌아감. 해당 코드는 에서 가져왔고, 제가 class 이름 등 약간 수정함.
아래와 같은 코드로 잘 동작했었는데, 최근에 뭔가 바뀐건지 AWS server 에서는 잘 동작을 안함. Error 잡는 중. 혹시 아시는 분 있으면 도와주세요~!
AWS 의 Outbound rule (아웃바운드 규칙) 을 잘 설정해줘야 했었음. SMTP port 가 587 을 기본적으로 이용하던데, 기존의 Outbound rule 에서는 1024 - 65XXX 까지 포트만 열어놨었어서 timeout 이 발생한 것인듯. 친구 구경렬의 도움으로 해!결! 땡큐~!
AWS Windows Server specification/version
- https://mvnrepository.com/artifact/com.sun.mail/jakarta.mail/2.0.1
- javamail.java.net - API docs - Package com.sun.mail.smtp summary
- developers.google.com - Google App Engine - Java - Using JavaMail to Send Mail
- stackoverflow.com - Send email using java, 2010-09-06, asked by Mohit Bansal.
// I used the answer by Cheok Yan Cheng. The code is written by doraemon (the same person??).
반응형
'[IT|Programming] > HTML related' 카테고리의 다른 글
HTML CSS composes, and pseudo-element :after, :active:after, and transition (0) | 2024.04.23 |
---|---|
순수한 완전 쉬운 편집 (SEE: Super Easy Edit) 문서K (Markdown: 마크다운): 사용 설명서. (1) | 2024.04.23 |
HTML a href tag with onclick return (2) | 2024.04.07 |
v.qq.com 동영상 퍼오기 (1) | 2024.02.18 |
.webp, .webm, .avif, .mp4 를 img tag, video tag 로 로딩 테스트 (Loading test) (5) | 2024.02.18 |
HTML 에서 동영상 연속 재생하기 (playlist, shuffle, replay) (0) | 2024.02.11 |
Getting Data from Google Spreadsheet or Excel (1) | 2024.02.09 |
http/https 링크
및 수식 (\ [ Outline 수식 \ ]
,\ ( inline 수식 \ )
::\
이후 띄어쓰기 없이) 을 넣으실 수 있습니다. 또한 code 는```
시작,```/
마지막으로 감싸 주시면 pretty-printed 되어서 나타납니다.```[.lang-js.scrollable.no-linenums]
같이 언어를 선택해 주실수도 있고, 긴 수식의 경우 scroll bar 가 생기게 만드실 수도 있습니다. .no-linenums 로 line numbering 을 없앨수도 있습니다.댓글 입력 후 rendering 된 형태를 보시려면, Handle CmtZ (단축키: N) 버튼을 눌러주세요. 오른쪽 아래 Floating Keys 에 있습니다. 아니면 댓글 젤 아래에 버튼이 있습니다.