본문 바로가기
오류 해결

java mail 전송 시 한글이 깨지는 경우

by Empering 2020. 4. 10.
반응형

spring 에서 JavaMailSender 이용 메일 전송시 한글이 깨지는 경우 발생

 

MimeMessagePreparator의 setSubject, setText 메서드를 실행할때 인자로 추가 charset을 지정해주면 된다.

 

setSubject, setText 메서드가 charset 없이도 호출가능하도록 오버로딩 되어있기때문에 빼먹고 호출하는 것에 주의 해야할것같다.

 

<charset을 적용한 코드>

package common.service;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

@Component
public class MailService {
	private Logger logger = LogManager.getLogger(MailService.class);
	
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${saro.mail.smtp.mail}")
    String form;

    public boolean sendMail(String to, String subject, String content) {
    	
        MimeMessagePreparator preparator = mimeMessage -> {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setFrom(new InternetAddress(form));
            mimeMessage.setSubject(subject, "utf-8");
            mimeMessage.setText(content, "utf-8", "html");
        };
        
        try {
            javaMailSender.send(preparator);
            return true;
        }
        catch (MailException me) {            
            logger.error("메일발송실패", me);
            return false;
        }
    }
}

 

<MimeMessage.java setText 코드>

    /**
     * Convenience method that sets the given String as this
     * part's content, with a MIME type of "text/plain". If the
     * string contains non US-ASCII characters. it will be encoded
     * using the platform's default charset. The charset is also
     * used to set the "charset" parameter.<p>
     *
     * Note that there may be a performance penalty if
     * <code>text</code> is large, since this method may have
     * to scan all the characters to determine what charset to
     * use. <p>
     *
     * If the charset is already known, use the
     * <code>setText</code> method that takes the charset parameter.
     *
     * @param	text	the text content to set
     * @exception	MessagingException	if an error occurs
     * @see	#setText(String text, String charset)
     */
    @Override
    public void setText(String text) throws MessagingException {
	setText(text, null);
    }

    /**
     * Convenience method that sets the given String as this part's
     * content, with a MIME type of "text/plain" and the specified
     * charset. The given Unicode string will be charset-encoded
     * using the specified charset. The charset is also used to set
     * the "charset" parameter.
     *
     * @param	text	the text content to set
     * @param	charset	the charset to use for the text
     * @exception	MessagingException	if an error occurs
     */
    @Override
    public void setText(String text, String charset)
			throws MessagingException {
	MimeBodyPart.setText(this, text, charset, "plain");
    }

    /**
     * Convenience method that sets the given String as this part's
     * content, with a primary MIME type of "text" and the specified
     * MIME subtype.  The given Unicode string will be charset-encoded
     * using the specified charset. The charset is also used to set
     * the "charset" parameter.
     *
     * @param	text	the text content to set
     * @param	charset	the charset to use for the text
     * @param	subtype	the MIME subtype to use (e.g., "html")
     * @exception	MessagingException	if an error occurs
     * @since	JavaMail 1.4
     */
    @Override
    public void setText(String text, String charset, String subtype)
                        throws MessagingException {
	MimeBodyPart.setText(this, text, charset, subtype);
    }
    
    

 

<MimeMessage.java setSubject 코드>

    /**
     * Set the "Subject" header field. If the subject contains 
     * non US-ASCII characters, it will be encoded using the 
     * platform's default charset. If the subject contains only 
     * US-ASCII characters, no encoding is done and it is used 
     * as-is. If the subject is null, the existing "Subject" field
     * is removed. <p>
     *
     * The application must ensure that the subject does not contain
     * any line breaks. <p>
     *
     * Note that if the charset encoding process fails, a
     * MessagingException is thrown, and an UnsupportedEncodingException
     * is included in the chain of nested exceptions within the
     * MessagingException.
     *
     * @param 	subject		The subject
     * @exception	IllegalWriteException if the underlying
     *			implementation does not support modification
     *			of existing values
     * @exception	IllegalStateException if this message is
     *			obtained from a READ_ONLY folder.
     * @exception	MessagingException for other failures
     */
    @Override
    public void setSubject(String subject) throws MessagingException {
	setSubject(subject, null);
    }

    /**
     * Set the "Subject" header field. If the subject contains non 
     * US-ASCII characters, it will be encoded using the specified
     * charset. If the subject contains only US-ASCII characters, no 
     * encoding is done and it is used as-is. If the subject is null, 
     * the existing "Subject" header field is removed. <p>
     *
     * The application must ensure that the subject does not contain
     * any line breaks. <p>
     *
     * Note that if the charset encoding process fails, a
     * MessagingException is thrown, and an UnsupportedEncodingException
     * is included in the chain of nested exceptions within the
     * MessagingException.
     *
     * @param	subject		The subject
     * @param	charset		The charset 
     * @exception		IllegalWriteException if the underlying
     *				implementation does not support modification
     *				of existing values
     * @exception		IllegalStateException if this message is
     *				obtained from a READ_ONLY folder.
     * @exception		MessagingException for other failures
     */
    public void setSubject(String subject, String charset)
			throws MessagingException {
	if (subject == null) {
	    removeHeader("Subject");
	} else {
	    try {
		setHeader("Subject", MimeUtility.fold(9,
		    MimeUtility.encodeText(subject, charset, null)));
	    } catch (UnsupportedEncodingException uex) {
		throw new MessagingException("Encoding error", uex);
	    }
	}
    }
반응형

댓글