> Java > java지도 시간 > 본문

Java로 이메일 첨부 파일 보내기

PHPz
풀어 주다: 2024-08-30 15:54:11
원래의
388명이 탐색했습니다.

다음 문서에서는 Java로 이메일 첨부 파일 보내기에 대한 개요를 제공합니다. 이메일 서비스 제공업체의 자격 증명과 이메일을 연결하는 기능은 이메일 첨부 파일을 보내는 기능을 활성화하는 것입니다. 이를 완료하려면 이메일 호스트 서비스를 사용해야 하며, 그 후 이메일 호스트, 포트, 사용자 이름 및 비밀번호를 입력하여 세션 개체를 생성해야 합니다. 이메일 호스트 서비스는 또한 전화 또는 기타 SMTP 테스트 서버를 활용할 수 있는 코드와 함께 이러한 모든 사양을 추가로 제공하고 JavaMail에 대한 구성 및 인증을 관리하기 위해 세션 개체가 연결 팩토리로 작동합니다.

Java로 이메일 첨부 파일 보내기

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

주요 시사점

  • JavaMail API는 첨부 파일이 포함된 이메일을 보내는 데 BodyPart, MimeBodyPart 등과 같은 다양하고 유용한 클래스를 제공합니다.
  • 이 예제를 이해하기 전에 JavaMail API의 이메일 전송 단계를 알아보십시오.
  • JavaMail API를 사용하여 이메일을 보내려면 mail.jar 및 activate.jar이라는 두 개의 jar 파일을 로드해야 합니다.
  • 세션을 얻고 메시지의 기본 MimeMessage 개체에 보낸 사람, 받는 사람, 제목을 설정합니다.
  • MimeMultipart 객체 생성. 이제 이 멀티파트 객체에는 실제 메시지가 포함된 위의 messageBodyPart가 포함되어야 합니다.
  • Transport 객체를 활용하여 메시지를 보냅니다.

Java에서 이메일 첨부 파일 보내기 개요

JavaMail API는 첨부 파일이 포함된 이메일을 보내는 데 BodyPart 및 MimeBodyPart와 같은 다양하고 유용한 클래스를 제공합니다. JavaMail API의 이메일 전송 단계를 이해하고 JavaMail API를 사용하여 이메일을 보내려면 다음 두 개의 jar 파일을 로드해야 합니다.

  • Mail.jar
  • Activation.jar

그럼 이제 Session 개체가 있으므로 MimeMessage 및 MimeBodyPart 개체를 만들어 보겠습니다.

이메일 메시지를 생성하기 위해 다음 개체를 사용합니다.

  • 세션 개체에 대한 작성 메시지를 가져옵니다.
  • MimeBodyPart 개체를 생성하고 그 안에 메시지 텍스트를 지정합니다. 다른 MimeBodyPart 개체를 만들고 여기에 DataHandler 개체를 추가합니다. Multipart 개체를 만들고 여기에 MimeBodyPart 개체를 포함합니다.
  • 멀티파트 개체를 메시지 개체로 설정하여 메시지를 보냅니다.

추가로 Java 이메일 프로그램의 단계는 다음과 같습니다.

  • javax.mail.Session 유형의 객체 만들기
  • Javax.mail.internet의 개발
  • 수신자의 이메일 주소, 이메일 제목, 회신 이메일, 이메일 본문, 첨부 파일 등 여러 속성을 설정해야 하는 MimeMessage 개체
  • javax.mail.Transport를 사용하여 이메일 메시지 보내기

Java에서 이메일 첨부파일을 보내는 방법은 무엇입니까?

이메일 서비스 제공업체의 자격 증명을 구성해야 합니다. 그런 다음 이메일 호스트, 포트, 사용자 이름 및 비밀번호를 입력하여 세션 개체를 만듭니다. 이메일 호스트 서비스는 이러한 모든 세부 사항을 제공합니다. 코드의 경우 가짜 SMTP 테스트 서버를 활용할 수 있습니다. JavaMail에 대한 구성 및 인증을 관리하기 위해 세션 개체는 연결 팩토리로 작동합니다. 이제 Session 객체가 있으므로 MimeMessage 및 MimeBodyPart 객체를 빌드합니다. 이메일 메시지를 생성하기 위해 다음 개체를 사용합니다.

코드:

Message testmsg = new MimeMessage(sess);
testmsg.setFrom(new InternetAddress(fromaddr));
testmsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
testmsg.setSubject("Welcome to our Test Site");
로그인 후 복사

위 코드는 MimeMessage 세션 객체의 도움으로 메시지 서비스를 생성하는 데 도움이 됩니다. 세션(sess)을 메시지 큐의 매개변수로 전달할 수 있습니다. 인스턴스의 도움으로 보낸 사람 주소나 보낸 사람 목록을 전달하는 데 사용되는 setFrom()이라는 메서드를 호출할 수 있습니다. 동일한 인스턴스에서 To 메일 수신자를 호출하는 RecipientType이라는 추가 메소드와 함께 Message 클래스와 같은 매개변수 전달을 사용하여 setRecipients()라는 다른 메소드를 호출할 수 있으며 추가로 수신자 주소를 전달하기 위한 기본 메소드인 구문 분석(to)을 사용하여 InternetAddress를 호출할 수 있습니다. setSubject()는 Message 클래스 인스턴스에 문자열 값을 전달합니다. MimeMessage 개체는 위의 발췌문에서 from, to 및 subject를 포함하여 필요한 정보와 함께 생성되었습니다. 다음으로 이메일 본문을 포함하는 MimeBodyPart 개체가 있습니다. 또한 메일 서비스에 첨부 파일을 추가하려면 이제 또 다른 MimeBodyPart를 구축해야 합니다.

코드:

MimeBodyPart mpart = new MimeBodyPart();
mpart.attachFile(new File("path/to/file"));
로그인 후 복사

The MimeBodyPart is the mail class body that created the instance and the same will be called for the method called attachFile() with additional parameters like to pass the new File object creation with file path parameters. TLS authentication is possible but different in several ways. As we can see, we are calling additional EmailUtil class methods to deliver email attachments and images even though we haven’t yet defined them.

Example of Sending Email Attachments in Java

Given below is the example mentioned:

Code:

package TestNG;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class NewTest{
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
Session sess = Session.<em><i>getDefaultInstance</i></em>(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]","xodbizaoiqijifre");
}
});
try{
MimeMessage msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress("[email protected]"));
msg.addRecipient(Message.RecipientType.<em><i>TO</i></em>,new InternetAddress("[email protected]"));
msg.setSubject("Welcome To My Domain");
BodyPart mbody = new MimeBodyPart();
mbody.setText("Your Message body is sent");
MimeBodyPart mbody1 = new MimeBodyPart();
String filename = "D://articles1.txt";
DataSource source = new FileDataSource(filename);
mbody1.setDataHandler(new DataHandler(source));
mbody1.setFileName(filename);
Multipart mpart = new MimeMultipart();
mpart.addBodyPart(mbody);
mpart.addBodyPart(mbody1);
msg.setContent(mpart );
Transport.<em><i>send</i></em>(msg);
System.<em><i>out</i></em>.println("Your email is sent successfully");
}catch (MessagingException ex) {ex.printStackTrace();}
}
}
로그인 후 복사

Output:

Java로 이메일 첨부 파일 보내기

  • In the above example, we first set the properties class and call the required mail.smtp.host parameters.
  • By using the session class instance, we can call and validate the user details like username and password.
  • Default session class creation like MimeMessage, MimeBodyPart, and Multipart to connect the user communications.
  • Using try and catch block to get the exception if the condition is not satisfied.
  • The transport protocol and its method for sending the message along with the attachment.

FAQs

Given below are the FAQs mentioned:

Q1. Define sending email with an attachment.

Answer: When enabling the functionality of sending email attachments, the email host, port, username, and password are entered after configuring the email with the email service provider’s credentials.

Q2. What is MimeMultipart in Java?

Answer: The abstract Multipart class is implemented by the MimeMultipart class, which employs MIME standards for multipart data.

Q3. What are the steps to follow sending email with an attachment?

Answer: Get the compose message for the session object.

Create a MimeBodyPart object and specify the message text in it. Create another MimeBodyPart object and add a DataHandler object to it. Create a Multipart object and include MimeBodyPart objects in it.

Send a message by setting the multipart object to the message object.

Conclusion

To obtain the session object, which contains all of the host’s data, including hostname, username, and password. Write the message, the message along with the attachment, and send it. The JavaMail API provides a platform- and protocol-neutral foundation for building mail and messaging applications. The JavaMail API makes a number of abstract classes defining the components of a mail system available.

위 내용은 Java로 이메일 첨부 파일 보내기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!