텍스트 대치 하다가 to, name 으로 한국어가 들어갔을 때 UTF-8로 인코딩 되지 않아 오류가 발생한 경우입니다. 

{ 
	"to": ["example@example.com", "example@example.com"]
	, "sub": {
		"%name%": ["테스트", "테테"] 
	} 
}

A message was received from this address by our systems that had errors in the SMTPAPI header, and cannot be processed due to the following:

 - invalid JSON

If you require assistance in working with the SendGrid API, please contact us at support@sendgrid.com

 


아래 구문으로 encodeText 처리하여 넘겨주면 정상적으로 메일 발송 성공을 확인할 수 있습니다.

message.addHeader("X-SMTPAPI", MimeUtility.encodeText(smtpJson));


Multipart multipart = new MimeMultipart("alternative");
BodyPart part = new MimeBodyPart();
message.addHeader("X-SMTPAPI", MimeUtility.encodeText(smtpJson));
part.setContent(content, "text/html; charset=utf-8");
multipart.addBodyPart(part);
message.setContent(multipart);

 

 

 

SMTP를 이용해 다량 메일을 보는 경우 발송 메일 html 내 건별 텍스트 대치를 하고 싶었습니다. 

회원별 이름이나 닉네임 등을 변경하여 OOO님 이런 식으로 보내고 싶었어요-

Sendgrid 에서 Customizing your send 라는 걸 지원하더라구요-

 

{
  "to": ["example@example.com", "example@example.com"],
  "sub": {
    "%name%": ["Ben", "Joe"]
  }
}

 

JSON 방식으로 위 값처럼 만들어서 보내주면 됩니다~ 

아래 방식으로 JSONObject에 담아 String으로 변환하여 보내줍니다.

List<Map> rstList = [DB에서 받아온 데이터];
List<String> to = new ArrayList<String>(); // 받는사람 email
List<String> name = new ArrayList<String>(); // 받는사람 닉네임

for (Map map: rstList) {
    if(map.get("e-mail") != null && map.get("name") != null) { // 두 값 모두 필수 이기 때문에 if문 추가
        to.add(map.get("email").toString());
        name.add(map.get("name").toString());
    }
}

JSONObject json = new JSONObject();
JSONObject jsonSub = new JSONObject();
json.put("to", to);
jsonSub.put("%name%", name);
json.put("sub", jsonSub);

String jsonRst = json.toString();

 

헤더에 전달하는 방법 : message.addHeader("X-SMTPAPI", jsonRst);

Multipart multipart = new MimeMultipart("alternative");
BodyPart part = new MimeBodyPart();
message.addHeader("X-SMTPAPI", jsonRst);
part.setContent(content, "text/html; charset=utf-8");
multipart.addBodyPart(part);
message.setContent(multipart);

 

 

SMTP 를 이용한 발송은 아래 페이지를 참고해서 작성했습니다.

https://docs.microsoft.com/ko-kr/azure/store-sendgrid-java-how-to-send-email#how-to-use-the-javaxmail-libraries

 

SendGrid 메일 서비스를 사용하는 방법(Java)

Azure에서 SendGrid 메일 서비스를 사용하여 메일을 보내는 방법을 알아봅니다. 코드 샘플은 Java로 작성되었습니다.

docs.microsoft.com

 

 

 

 

 

https://sendgrid.com/docs/for-developers/sending-email/building-an-x-smtpapi-header/#customizing-your-send-filters

 

Building an X-SMTPAPI Header

Learn how to build email content, add recipients and schedule your send.

sendgrid.com

 

 

인텔리제이에서 Sendgrid 메일 발송 테스트 진행 중 한글 깨짐 관련 오류가 발생하여

발송인 메일로 다음과 같은 오류 메일이 왔습니다. 


A message was received from this address by our systems that had errors in the SMTPAPI header, and cannot be processed due to the following:

 - unknown charset 'ms949'

If you require assistance in working with the SendGrid API, please contact us at support@sendgrid.com

 

확인해보니 인텔리제이에서 컴파일이 UTF-8로 되지 않아서 발생하는 현상이었습니다.

help - Edit Custom VM Options.. 를 열어서

 

아래 문구를 추가하고 인텔리제이 재시작~

-Dfile.encoding=UTF-8

 

안 되면 .. 다시 Setting-Editor-File Encodings에서 UTF-8로 설정..

 

그래도 안 되면.. 상단 설정에 Edit Configurations.. 들어가서

 

저는 이걸 다 하고.. 해결되었습니다ㅎㅎ



다음 사이트를 참고하여 셋팅함

https://docs.microsoft.com/ko-kr/azure/store-sendgrid-java-how-to-send-email

 

SendGrid 메일 서비스를 사용하는 방법(Java)

Azure에서 SendGrid 메일 서비스를 사용하여 메일을 보내는 방법을 알아봅니다. 코드 샘플은 Java로 작성되었습니다.

docs.microsoft.com

 

처음엔 다음과 같이 다른 SMTP 제공 사이트과 동일하게 UserId, PWD를 이용해 시도해보았으나, 오류가 발생했습니다.

private static final String SMTP_AUTH_USER = "[Sandgrid 로그인 아이디]";
private static final String SMTP_AUTH_PWD = "[Sandgrid 로그인 비밀번호]";

<오류내용>

535 Authentication failed: Basic authentication is not allowed with 2FA enabled. 
To fix, see 

https://sendgrid.com/docs/for-developers/sending-email/authentication/#basic-authentication

 해결방법

private static final String SMTP_AUTH_USER = "apikey"; // 
private static final String SMTP_AUTH_PWD = "[SG. 로 시작하는 API_KEY]"

로 변경해주니 정상동작했습니다.

 

private static final String SMTP_HOST_NAME = "smtp.sendgrid.net"; // 그냥 텍스트
private static final String SMTP_AUTH_USER = "apikey"; // 그냥 텍스트  
// sandgrid 사이트에서 발급받은 API_KEY (https://app.sendgrid.com/settings/api_keys)
private static final String SMTP_AUTH_PWD = "[API_KEY]"; 

private static class SMTPAuthenticator extends javax.mail.Authenticator {
  public PasswordAuthentication getPasswordAuthentication() {
    String username = SMTP_AUTH_USER;
    String password = SMTP_AUTH_PWD;
    return new PasswordAuthentication(username, password);
  }
}
    
public static boolean SendMail() throws Exception {
		String fromMail = "[보내는사람Email(Sandgrid 에서 등록한, 검증된 이메일 정보 사용)]";
		String fromName = "[보내는사람이름]";
		String toMail = "[받는사람Email]";
		String title = "제목";
		String content = "<p>안녕,</p> <p><b>테스트</b>중이다</p><p>고마워,<br>존</br></p>";
		
		// SMTP 정보 셋팅
		Properties properties = new Properties();
		properties.put("mail.transport.protocol", "smtp");
		properties.put("mail.smtp.host", SMTP_HOST_NAME);
		properties.put("mail.smtp.port", 587);
		properties.put("mail.smtp.auth", "true");

		Authenticator auth = new SMTPAuthenticator();
		Session mailSession = Session.getDefaultInstance(properties, auth);
		try {
			MimeMessage message = new MimeMessage(mailSession);
			
			// 보낸사람 (Sandgrid 에서 등록한, 검증된 이메일 정보 사용)
            InternetAddress from = new InternetAddress(fromMail, fromName, "UTF-8");
            message.setFrom(from);
            // 받는사람
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
            // 제목
			message.setSubject(title);
			message.setSentDate(new java.util.Date());

			Multipart multipart = new MimeMultipart("alternative");
            // 내용(본문)
			BodyPart part = new MimeBodyPart();
			part.setContent(content, "text/html; charset=utf-8"); // 한글 깨지지 않도록 utf-8 추가
			multipart.addBodyPart(part);
			message.setContent(multipart);
			// 발송
            Transport transport = mailSession.getTransport();
			transport.connect();
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
			return true;
		} catch (MessagingException ex){
			System.out.println("메일 발송 에러 : " + ex);
		}
		return false;
	}

 

 

https://sendgrid.com/docs/for-developers/sending-email/authentication/#basic-authentication

 

Authentication

Authenticating with the SendGrid API.

sendgrid.com

 

Sendgrid 메일을 JAVA에서 적용하는 경우,

401 오류 : The provided authorization grant is invalid, expired, or revoked 오류는,

{"errors":[{"message":"The provided authorization grant is invalid, expired, or revoked"
,"field":null,"help":null}]}
{Strict-Transport-Security=max-age=600; includeSubDomains
, Server=nginx, Access-Control-Allow-Origin=https://sendgrid.api-docs.io,
Access-Control-Allow-Methods=POST, Connection=keep-alive
, X-No-CORS-Reason=https://sendgrid.com/docs/Classroom/Basics/API/cors.html, 
Content-Length=116, Access-Control-Max-Age=600, Date=Mon, 17 May 2021 07:42:51 GMT
, Access-Control-Allow-Headers=Authorization, 
Content-Type, On-behalf-of, x-sg-elas-acl, Content-Type=application/json}

SendGrid sg = new SendGrid(System.getenv("[API_KEY]"));

로 제공된 부분에 System.getenv("[API_KEY]") 에서 null을 반환하여 오류가 발생합니다. 

System.getenv("") 구문을 제거 후 정상동작을 확인할 수 있습니다.

        Email from = new Email("[sendgrid에서 등록한, 검증된 보내는 사람 메일]");
		Email to = new Email("[받는사람메일]");
		String subject = "Sending with Twilio SendGrid is Fun";
		Content content = new Content("text/plain", "and easy to do anywhere, even with Java");

		Mail mail = new Mail(from, subject, to, content);
		SendGrid sg = new SendGrid("[API_KEY]");
		Request request = new Request();
		try {
			request.setMethod(Method.POST);
			request.setEndpoint("mail/send");
			request.setBody(mail.build());
			Response response = sg.api(request);
			System.out.println(response.getStatusCode());
			System.out.println(response.getBody());
			System.out.println(response.getHeaders());
		} catch (IOException ex) {
			throw ex;
		}

 

 


 

403 오류의 경우, "[sendgrid에서 등록한, 검증된 보내는 사람 메일]" 이 일치하지 않아서 발생하는 오류입니다. 

{"errors":[{"message":"The from address does not match a verified Sender Identity. 
Mail cannot be sent until this error is resolved. 
Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements","field":"from","help":null}]}

관리 사이트 내에서 'https://app.sendgrid.com/settings/sender_auth' 로 접근하여 이메일을 등록해주고, 해당 메일로 전송된 인증 메일을 통해 검증을 완료한 후 from 메일에 작성하여 발송테스트를 진행하면 됩니다.

아래 이미지와 같이 검증된! 마크가 있어야 완료 상태입니다.

 

API KEY 발급은 https://app.sendgrid.com/settings/api_keys 페이지로 접근하여

 

우측 API 키 생성 클릭

키 이름을 설정해주고, 전체 엑세스 [Full Access] 를 선택 

Create & View 클릭 시 바로 API키가 생성되며 다시 확인할 수 없으므로 잘 저장해두셔야 합니다. 

이 API_KEY를 이용해 메일을 발송합니다.

+ Recent posts