2013-07-06 4 views
1

다음 코드를 사용하고 Javamail API를 사용하여 전자 메일을 보낼 수 있습니다.이 API를 통해 "FROM"을 "yahoo 전자 메일 ID"로 사용하여 모든 전자 메일 ID로 보낼 수 있습니다. 코드 :jsp에서 문의 양식을 만드시겠습니까?

mailFORM.html

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
    <!DOCTYPE html> 
    <html> 
    <head> 
    <title>Mail form in html</title> 
    </head> 
    <body> 
    <table border="1" width="50%" cellpadding="0" cellspacing="0"> 
    <tr> 
    <td width="100%"> 
    <form method="POST" action="mail.jsp"> 
    <table border="1" width="100%" cellpadding="0" cellspacing="0"> 
    <h1>Mail API</h1> 
    <tr> 
    <td width="50%"><b>To:</b></td> 
    <td width="50%"><input type="text" name="to" size="30"></td> 
    </tr> 
    <tr> 
    <td width="50%"><b>From:</b></td> 
    <td width="50%"><input type="text" name="from" size="30"></td> 
    </tr> 
    <tr> 
    <td width="50%"><b>Subject:</b></td> 
    <td width="50%"><input type="text" name="subject" size="30"></td> 
    </tr> 
    <tr> 
    <td width="50%"><b>Description:</b></td> 
    <td width="50%"><textarea name="description" type="text" 
cols="40" rows="15" size=100> 
    </textarea> 
    </td> 
    </tr> 
    <tr> 
    <td><p><input type="submit" value="Send Mail" name="sendMail"></td> 
    </tr> 
    </table> 
    </p> 
    </form> 
    </td> 
    </tr> 
    </table> 
    </body> 
    </html> 

mail.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
    <!DOCTYPE html> 
    <%@ page language="java" import="javax.naming.*,java.io.*,javax.mail.*, 
    javax.mail.internet.*,com.sun.mail.smtp.*"%> 
    <html> 
    <head> 
    <title>sending mail using contactus form</title> 
    </head> 
    <body> 
    <% 
    try{ 
    Session mailSession = Session.getInstance(System.getProperties()); 
    Transport transport = new SMTPTransport(mailSession,new URLName("smtp.mail.yahoo.com")); 
    transport = mailSession.getTransport("smtps"); 
    transport.connect("smtp.mail.yahoo.com",465,"[email protected]","myyahoopassword"); 
    MimeMessage m = new MimeMessage(mailSession); 
    m.setFrom(new InternetAddress(%><%request.getParameter("from")%><%)); 
    Address[] toAddr = new InternetAddress[] { 
    new InternetAddress(%><%request.getParameter("to")%><%) 
    }; 
    m.setRecipients(javax.mail.Message.RecipientType.TO, toAddr); 
    m.setSubject(%><%request.getParameter("subject")%><%); 
    m.setSentDate(new java.util.Date()); 
    m.setContent(%><%request.getParameter("description")%><%, "text/plain"); 

    transport.sendMessage(m,m.getAllRecipients()); 
    transport.close(); 
    out.println("Thanks for sending mail!"); 
    } 
    catch(Exception e){ 
    out.println(e.getMessage()); 
    e.printStackTrace(); 
    } 
    %> 
    </body> 

지금, 나는 "에서"TO "필드를 제거 할 수 있습니다있는 간단한 CONTACTUS 양식을 만들려면 mailFORM.html "명백한 이유로 파일. 방문자가 내 웹 사이트를 방문하고 FROM, NAME, SUBJECT 및 설명을 입력하여 "[email protected]"으로 이메일을 보내길 원하기 때문입니다.

그래서 어떻게 username과 passwod를 입력 할 때이 문제를 제거 할 수 있습니까? 내가 여기에 passred 코드를 만들 수 없기 때문에. 나는 다른 smtp를위한 별도의 코드를 만들 수 없다 ... VISITIR로서 나의 웹 사이트 contactus 페이지를 visting하는 것은 어떤 도메인으로부터의 그의 이메일을 입력하여 폼을 채울 수있다. 같은 회사의 특정 전자 메일-ID에 세부 사항을 보내이 같은 형태 (모든 익명의 웹 사이트를 복용)을 만듭니다 "[email protected]을"
http://www.tutorialspoint.com/about/contact_us.htm

답변

2

하드 코드 귀하의 JSP 파일에 이메일 ID를 넣으려면 좋은 방법이지만 JSP로 자바 코드를 작성하지 않으려면 메소드 호출 만 작성하십시오.

private final String TO_EMAIL = "[email protected]"; 

내 코드는 모든 SMTPS에서 작동합니다.

package com.naveed.workingfiles; 

import org.apache.commons.mail.DefaultAuthenticator; 
import org.apache.commons.mail.EmailAttachment; 
import org.apache.commons.mail.MultiPartEmail; 

public class Mail { 
String senderID; 
String senderPassword; 
String hostName; 
int portNumber; 
String attachmentPath; 
String subject; 
String body; 
String cc; 
String bcc; 


// #=============================================================================================# 
public String getBcc() { 
    return bcc; 
} 

// #=============================================================================================# 
public void setBcc(String bcc) { 
    this.bcc = bcc; 
} 

// #=============================================================================================# 
public String getCc() { 
    return cc; 
} 

// #=============================================================================================# 
public void setCc(String cc) { 
    this.cc = cc; 
} 

// #=============================================================================================# 
public String getBody() { 
    return body; 
} 

// #=============================================================================================# 
public void setBody(String body) { 
    this.body = body; 
} 

// #=============================================================================================# 
public String getSubject() { 
    return subject; 
} 

// #=============================================================================================# 
public void setSubject(String subject) { 
    this.subject = subject; 
} 

// #=============================================================================================# 

public String getSenderID() { 
    return senderID; 
} 

// #=============================================================================================# 
public void setSenderID(String senderID) { 
    this.senderID = senderID; 
} 

public String getSenderPassword() { 
    return senderPassword; 
} 

// #=============================================================================================# 
public void setSenderPassword(String senderPassword) { 
    this.senderPassword = senderPassword; 
} 

// #=============================================================================================# 
public String getHostName() { 
    return hostName; 
} 

// #=============================================================================================# 
public void setHostName(String hostName) { 
    this.hostName = hostName; 
} 

// #=============================================================================================# 
public int getPortNumber() { 
    return portNumber; 
} 

// #=============================================================================================# 
public void setPortNumber(int portNumber) { 
    this.portNumber = portNumber; 
} 

// #=============================================================================================# 
public String getAttachmentPath() { 
    return attachmentPath; 
} 

// #=============================================================================================# 
public void setAttachmentPath(String attachmentPath) { 
    this.attachmentPath = attachmentPath; 
} 

// #=============================================================================================# 
public void sendMail(String receiverId) { 

    try { 
     // this below commented line for the HTML body text 
     // MultiPartEmail htmlEmail = new HtmlEmail(); 
     // OR 
     // HtmlEmail email = new HtmlEmail(); 

     MultiPartEmail email = new MultiPartEmail(); 
     // setting the port number 
     email.setSmtpPort(getPortNumber()); 
     // authenticating the user 
     email.setAuthenticator(new DefaultAuthenticator(getSenderID(), 
       getSenderPassword())); 
     // email.setDebug(true); 
     email.setSSL(true); 
     // setting the host name 
     email.setHostName(getHostName()); 
     // setting the rciever id 

     email.addTo(receiverId); 

     // check for user enterd cc or not 
     if (getCc() != null) { 
      // add the cc 
      email.addCc(getCc()); 
     } 
     // check for user enterd bcc or not 
     if (getBcc() != null) { 
      // add the bcc 
      email.addBcc(getBcc()); 
     } 
     // setting the sender id 
     email.setFrom(getSenderID()); 
     // setting the subject of mail 
     email.setSubject(getSubject()); 
     // setting message body 
     email.setMsg(getBody()); 
     // email.setHtmlMsg("<h1>"+getBody()+"</h1>"); 

     // checking for attachment attachment 
     if (getAttachmentPath() != null) { 
      // add the attachment 
      EmailAttachment attachment = new EmailAttachment(); 
      attachment.setPath(getAttachmentPath()); 
      attachment.setDisposition(EmailAttachment.ATTACHMENT); 
      email.attach(attachment); 
     } 

     // send the email 
     email.send(); 
     // System.out.println("Mail sent!"); 
    } catch (Exception e) { 
     // System.out.println("Exception :: " + e); 
     e.printStackTrace(); 

    } 
}// sendmail() 
}// mail 

사용자 설정 이메일을 기준으로 모든 세분화 된 도메인 정보 (호스트 이름, 포트) 만 저장하면됩니다. 모든 필수 라이브러리를 다운로드하십시오.

+0

ok @ NAVEEED, 그래서 내가 언급 한 다른 것들 ... jsp에서 contactus 형식을 만들기 위해 서버의 사용자 이름/암호를 enetring하는 것을 피한다. 다시 게시판을 읽어주십시오 –

+0

@amanChawla 내 대답을 참조해야합니다 –

+0

ok nAvEeD, 저에게 많은 도움이 될 것입니다 ... 감사합니다 –

1

당신은 방금 Message.RecipientType.TO 변수를 하드 코어 할 수 있습니다.

어딘가에 당신이 할 때마다이 켜지지 당신이 그들에게 연락 할 수 있도록,하지만 코드에서 어딘가에 보낸 전자 메일을 포함해야합니다 정적 변수 MY_MAIL를 정의하고 대신 request.getParameter("to")

MY_MAIL를 사용할 수 있습니다.

또한

다른 몇 가지 고려 사항 :

  • 는 JSP 페이지에서 실제 자바 코드를 오토넷에 대해 읽어주세요, 당신이 구글에서 그만큼의 링크를 찾을 수 있습니다.
  • 클래스를 가져 오지만 더 이상 가져 오기를 사용하지 않습니다.
  • 코드에 쓸모가없는 %><%가 있습니다. 어디 있는지 알지 못합니다.
+0

당신이 언급 한 것을 고려하면 ... 나는 어딘가에 주소를 저장하는 것을 알고 있습니다. 다른 사양을 풀고 싶을 때까지. 내가 요구 한 것에 대답 해주십시오. 나는 귀하의 고려 사항을 따르려고합니다 –

+0

@AmanChawla 그건 이런 식으로 불가능합니다. 코드는 알려진 주소 (사용자 이름/암호 로그인 사용)에서 특정 대상으로 전자 메일을 보내는 방법을 보여줍니다. 실제로 사용자로 로그인하지 않습니다. 그래서 기본적으로 자신에게 메일을 보내는 것을 고려하십시오.예를 들어 웹 서버에서 웹 서버로, 웹 서버에서 개인 메일로 등등. – skiwi

+0

ok @skiwi, 어떻게하면됩니까?이 사이트의 많은 사용자와 다른 사용자는 동일한 방법으로 사용자 이름 그리고 passowrd. 그래서, 나는 contactus/feedback 양식이 jsp에서 이메일 주소, 제목 및 메시지를 입력하기 만하면 방문자가 전자 메일을 어떻게 작성하는지 궁금합니다. –

관련 문제