programing

Laravel 메일: 보기 대신 문자열 전달

goodcopy 2022. 9. 25. 22:56
반응형

Laravel 메일: 보기 대신 문자열 전달

라라벨을 사용하여 확인 메일을 보내고 싶습니다.laravel Mail::send() 함수는 시스템상의 파일에 대한 경로만 받아들이는 것 같습니다.문제는 mailtemplate가 시스템상의 파일이 아닌 데이터베이스에 저장되어 있다는 것입니다.

일반 콘텐츠를 이메일로 전달하려면 어떻게 해야 합니까?

예:

$content = "Hi,welcome user!";

Mail::send($content,$data,function(){});

2022년 7월 20일 업데이트: Larabel의 최신 버전에 대해서는setBody()Mail::send()는 '보다 낫다'로되었습니다.text() ★★★★★★★★★★★★★★★★★」html()★★★★★★★★★★★★★★★★★★.

업데이트: Larabel 5에서는 사용할 수 있습니다.raw★★★★

Mail::raw('Hi, welcome user!', function ($message) {
  $message->to(..)
    ->subject(..);
});

방법은 다음과 같습니다.

Mail::send([], [], function ($message) {
  $message->to(..)
    ->subject(..)
    // here comes what you want
    ->setBody('Hi, welcome user!'); // assuming text/plain
    // or:
    ->setBody('<h1>Hi, welcome user!</h1>', 'text/html'); // for HTML rich messages
});

HTML 메일의 경우

Mail::send(array(), array(), function ($message) use ($html) {
  $message->to(..)
    ->subject(..)
    ->from(..)
    ->setBody($html, 'text/html');
});

질문과는 직접 관련이 없지만 커스텀HTML 버전을 유지하면서 전자 메일의 플레인텍스트버전 설정을 검색하는 경우는, 다음의 예를 사용할 수 있습니다.

Mail::raw([], function($message) {
    $message->from('contact@company.com', 'Company name');
    $message->to('johndoe@gmail.com');
    $message->subject('5% off all our website');
    $message->setBody( '<html><h1>5% off its awesome</h1><p>Go get it now !</p></html>', 'text/html' );
    $message->addPart("5% off its awesome\n\nGo get it now!", 'text/plain');
});

"하지만 첫 번째 인수를 일반 텍스트로 설정하지 그래요?"라고 묻는다면 테스트를 해봤더니 html 부분만 가져가고 원시 부분은 무시합니다.

해야 하는 에서는 ''를 .use().

Mail::raw([], function($message) use($html, $plain, $to, $subject, $formEmail, $formName){
    $message->from($fromEmail, $fromName);
    $message->to($to);
    $message->subject($subject);
    $message->setBody($html, 'text/html' ); // dont miss the '<html></html>' or your spam score will increase !
    $message->addPart($plain, 'text/plain');
});

도움이 되시길 바랍니다.

클래스는 합니다.addContent 다른 으로 하다, 하다, 하다, 하다, 하다, 하다라고 합니다.views->make()따라서 해당 이름의 보기를 로드하려고 하므로 컨텐츠 문자열을 직접 전달하지 않습니다.

할 은 단순히 입니다.$content

// mail-template.php
<?php echo $content; ?>

그런 다음 실행 시 해당 보기에 문자열을 삽입합니다.

$content = "Hi,welcome user!";

$data = [
    'content' => $content
];

Mail::send('mail-template', $data, function() { });

해라

public function build()
{
    $message = 'Hi,welcome user!'
    return $this->html($message)->subject($message);
}

비슷한 문제가 있었습니다.내 이메일의 HTML 및/또는 보통 텍스트가 뷰에 의해 구축되지 않아 더미 뷰를 만들고 싶지 않았습니다(@Mathew Ododoyin의 제안대로).

쓰시면 .$this->html()메시지의 HTML 콘텐츠를 설정하는데, HTML 콘텐츠와 일반 텍스트 콘텐츠를 모두 전자 메일에 포함시키려면 어떻게 해야 합니다.

도 ★★★★★★★★★★★★★★★.$this->text()뷰만 표시하지만 다음 방법으로 이 문제를 해결했습니다.

$this->text(new HtmlString('Here is the plain text content'));

'아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,HTMLString뷰 대신.

당신이 알다시피.

메일 파일만 대기열에 넣을 수 있습니다.

,을 ShouldQueue

1) 첫째, 항상 다음을 수행해야 합니다.

php artisan queue:restart

에는 2) 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아,html) (라벨 5.8로 표시)

public function build(): self
{
    return $this
            ->html('
                <html>
                    <body>
                        ForwardEmail
                    </body>
                </html>
            ')
            ->subject(config('app.name') . ' ' . 'email forwarded')
            ->attachData($this->content, 'email.eml', [
                'mime' => 'application/eml',
    ]);
}

우편물을 사용했다면.빌드 방식에서는 다음과 같은 작업을 수행할 수 있습니다.

public function build()
{
 
    return $this->view('email')
        ->with(['html'=>'This is the message']);
}

다음 뷰를 만들면 .email.blade.php리소스 폴더에 저장하십시오.

그런 다음 블레이드에서는 larabel 블레이드 구문을 사용하여 문자열을 참조할 수 있습니다.

 <html>
    <body>
      {{$html}}
    </body>
  </html>

또는

 <html>
    <body>
      {!!$html!!}
    </body>
 </html>

raw 텍스트에 HTML 마크업이 포함되어 있는 경우 데이터베이스에 저장되어 있는 템플릿을 가지고 있으며 Larabel에 있는 Mailables 클래스를 이용하고 싶은 사용자에게 효과가 있기를 바랍니다.

Laravel Mailables를 사용하여 원시 html, 텍스트 등을 전송하려면 다음 작업을 수행합니다.

Mailable 및 Mailable에서 Mailable->send()를 덮어씁니다.이전 응답의 메서드를 사용합니다.

send([], [], function($message){ $message->setBody() } )

빌드 함수에서 $this->view()를 호출할 필요가 없습니다.

메모: 다음 답변은 유연한 접근방식을 원하는 분들을 위한 것입니다.즉, (라벨 템플릿의 유무에 관계없이)

템플릿 사용

 $payload['message'] = View::make('emails.test-mail',$data)->render();

템플릿 없음

$payload['message'] = "lorem ipsum";


Mail::raw([], function ($mail) use ($payload) {
    $mail->from($payload['from_email'])
        ->to($payload['to'])
        ->setBody($payload['message'], 'text/html')
        ->cc($payload['cc'])
        ->bcc($payload['bcc'])
        ->subject($payload['subject']);
    foreach ($payload['attachments'] as $file){
        $mail->attach($file);
    }
});

이는 Mailable 구현 내에서 플레인 텍스트 및 html 콘텐츠 파트를 사용하여 수행할 수 있습니다.

  public function build() {

    // Text and html content sections we wish to use in place of view output
    $bodyHtml = ...
    $bodyText = ...

    // Internally, Mailer::renderView($view) interprets $view as the name of a blade template
    // unless, instead of string, it is set to an object implementing Htmlable,
    // in which case it returns the result $view->toHtml()
    $htmlViewAlternative = new class($bodyHtml) implements Htmlable {
      protected string $html;
      public function __construct($html) {
        $this->html = $html;
      }
      public function toHtml(): string {
        return $this->html;
      }
    };

    // We can now set both the html and text content sections without
    // involving blade templates. One minor hitch is the Mailable::view($view)
    // documents $view as being a string, which is incorrect if you follow
    // the convoluted downstream logic. 
    /** @noinspection PhpParamsInspection */
    return $this
      ->to(...)
      ->from(...)
      ->subject(...)
      ->view([
        'html' => $htmlViewAlternative,
        'raw' => $bodyText
      ]);
  }

Laravel 메일 가능에는->html()대신 사용하는 기능->view()o와 함께 사용할 수 있습니다.->text()

larabel 9는 뷰 없이 HTML을 전송할 수 있는 기능을 내장했습니다.다음은 예를 제시하겠습니다.

\Illuminate\Support\Facades\Mail::html($content, function ($message) {
    $message->to("email@example.com")
        ->subject("Test dev 4")
        ->from("email@example.com");
});

또한 승인된 답변을 사용할 경우 다음과 같이 반환됩니다.

Symfony\Component\Mime\Message:setBody(): 인수 #1($body)은 유형이어야 합니다.Symfony\Component\Mime\AbstractPart, 문자열 지정. /Users/yaskur/Sites/laravel/mail-builder/vendor/laravel/frame/src/Iluminate/Support/Trits/ForwardsCalls. 페이지 23번으로 호출됩니다.

라라벨이 이메일을 보내기 위해 새로운 라이브러리를 사용하기 때문에 발생합니다.이전에는 Swiftmailer를 사용했지만 지금은 Symfony Mailer를 사용합니다.HTML 이메일을 보기 없이 보내려면 다음 코드를 사용할 수도 있습니다.

Mail::raw("", function ($message) use ($content) {
    $body = new \Symfony\Component\Mime\Part\TextPart($content);
    $message->to("dyas@example.com")
        ->subject("Test dev")
        ->from("no-reply@example.com")
        ->setBody($body);
});

언급URL : https://stackoverflow.com/questions/26139931/laravel-mail-pass-string-instead-of-view

반응형