Este exemplo compartilha o código específico de Java usando o soquete para implementar o protocolo SMTP para enviar e -mails para sua referência. O conteúdo específico é o seguinte
pacote e -mail; importar java.io.bufferedReader; importar java.io.ioException; importar java.io.inputStream; importar java.io.inputStreamReader; importar java.io.outputStream; importação java.io.printWriter; import java.io.read; java.util.list; importar java.util.list; importar org.apache.commons.codec.binary.base64; public class Mail {public static void main (string [] args) lança IoException {Mail Mail = new Mail (); Mail.SetSmtpServer ("smtp.qq.com"); Mail.setFraild ("1344364 ****@qq.com"); Mail.addtomail ("105648 ****@qq.com"); Mail.addtomail ("long *******@sina.com"); Mail.setUserName ("134364 ****"); Mail.setPassword ("************"); Mail.SetSubject ("Test Mail"); Mail.setContent ("<H1> Olá </h1> <br/> <img src =/" https://www.baidu.com/img/baidu_jgylogo3.gif?v=39549282.gif/ "/>"); Mail.setShowloG (true); Mail.Send (); System.out.println ("End do programa"); } / ** Assunto do e -mail ** / Assunto da String Private; / ** Enviar deste endereço **/ String privada do MAIL; / ** Nome de usuário **/ nome de string privado nome de usuário; / ** Senha de login **/ senha de sequência privada; / ** Endereço do servidor SMTP **/ String privada smtpServer; / ** porta do servidor SMTP (padrão: 25) **/ privado int smtpport = 25; / ** Todos os endereços enviados ao TOMAIL **/ Lista privada <String> TOMAIL; / ** Conteúdo de correio **/ Conteúdo da String Private; / ** se você deve exibir o log **/ ShowLog booleano privado; public void addTomail (string Mail) {if (tomail == null) TOMAIL = new ArrayList <String> (); tomail.add (correio); } public void send () {if (smtpServer == null) {throw new RunTimeException ("smtpServer não pode estar vazio"); } if (nome de usuário == null) {lança a nova RunTimeException ("nome de usuário não pode estar vazio"); } if (senha == null) {lança a nova run timeException ("senha não pode estar vazia"); } if (Frommail == null) {lança a nova RunTimeException ("Frommail não pode estar vazio"); } if (tomail == null || tomail.isEmpty ()) {lança a nova execução de tempo decepção ("TOMAIL não pode estar vazio"); } if (Content == null || tomail.isempty ()) {lança a nova RunTimeException ("O conteúdo não pode estar vazio"); } Soquete de soquete = nulo; InputStream in = null; OutputStream out = null; tente {soquete = novo soquete (smtpServer, smtpport); Socket.SetSotimeout (3000); in = soket.getInputStream (); out = Socket.getOutputStream (); } catch (ioexception e) {lança nova runtimeException ("conectar -se a" + smtpServer + ":" + smtpport + "falhou", e); } BufferReaderProxy Reader = new BufferReaderProxy (new InputStreamReader (in), ShowLog); PrintWriterProxy Writer = New PrintWriterProxy (Out, ShowLog); leitor.showResponse (); writer.println ("helo" + smtpServer); leitor.showResponse (); writer.println ("Auth Login"); leitor.showResponse (); writer.println (new String (base64.EncodeBase64 (nome de usuário.getBytes ())); leitor.showResponse (); writer.println (new String (base64.EncodeBase64 (senha.getBytes ()))); leitor.showResponse (); writer.println ("Mail de:" + Frommail); leitor.showResponse (); for (string Mail: TOMAIL) {writer.println ("RCPT para:" + Mail); leitor.showResponse (); } writer.println ("dados"); writer.println ("Tipo de conteúdo: text/html"); if (sujeito! = null) {writer.println ("sujeito:" + sujeito); } writer.println ("de:" + Frommail); writer.print ("para:"); for (string Mail: TOMAIL) {writer.print (Mail + ";"); } writer.println (); writer.println (); writer.println (conteúdo); writer.println ("."); leitor.showResponse (); writer.println ("pare"); leitor.showResponse (); tente {socket.close (); } catch (ioexception e) {System.err.println ("Enviar o email completa, feche o erro do soquete:" + e.getMessage ()); }} public string getSBject () {retornar sujeito; } public void Setsubject (String sujeito) {this.subject = sujeito; } public string getFrail () {return frommail; } public void SetFrail (String Frommail) {this.FraMail = Frommail; } public String getStMtPerver () {return smtpServer; } public void SetsMtpServer (String SmtpServer) {this.smtpServer = smtpServer; } public int getSTMTPPort () {return smtpport; } public void Setsmtpport (int smtpport) {this.smtpport = smtpport; } public string getContent () {return content; } public void setContent (String content) {this.content = content; } Lista pública <String> getTomail () {return tomail; } public void SettOMail (List <String> TOMAIL) {this.Tomail = TOMAIL; } public string getUserName () {return userName; } public void setUserName (string userName) {this.username = nome de usuário; } public string getPassword () {return senha; } public void setPassword (string senha) {this.password = senha; } public boolean getShowlogl () {return showLog; } public void SetShowLog (Boolean ShowLog) {this.ShowloG = ShowLog; } classe estática printWriterProxy estende o printWriter {private boolean showRequest; public PrintWriterProxy (OutputStream Out, Boolean ShowRequest) {super (Out, True); this.showRequest = showRequest; } @Override public void println () {if (showRequest) System.out.println (); super.println (); } public void print (strings) {if (showRequest) System.out.print (s); super.print (s); }} classe estática bufferReaderProxy estende o buffersader {private boolean showResponse = true; public buffarredreaderProxy (leitor in, boolean showResponse) {super (in); this.ShowResponse = ShowResponse; } public void showResponse () {try {string line = readLine (); String number = line.substring (0, 3); int num = -1; tente {num = Integer.parseint (número); } catch (Exceção e) {} if (num == -1) {tiro novo RUNTimeException ("Erro de informação de resposta:" + linha); } else if (num> = 400) {lança nova run timeException ("Enviar e -mail falhou:" + linha); } if (showResponse) {System.out.println (linha); }} catch (ioexception e) {System.out.println ("Falha ao obter resposta"); }}}}O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.