bash or sh 여부에 따라 다르게 동작할 수 있음.

동일한 bash 더라도 버전에 따라 다르게 동작할 수 있음.

 

단일 조건일 때는 둘다 무관하지만 여러조건을 한 줄에 표현할 때 차이가 있음.

if [ 조건문 ] && [ 조건문 ] ; then
fi
if [[ 조건문 && 조건문 ]] ; then
fi

 

'프로그래밍 > ShellScript' 카테고리의 다른 글

[shell script] if  (0) 2019.04.20
디렉터리 존재여부 확인  (0) 2019.04.17

여친의 부탁으로 메일보내기 매크로를 작성했었다. 
맥에서 작성해서 줬는데 윈도우의 인코딩 문제란 ㄷㄷㄷ

Ref : docs.python.org/3/library/email.examples.html

 

email: Examples — Python 3.9.4 documentation

Here are a few examples of how to use the email package to read, write, and send simple email messages, as well as more complex MIME messages. First, let’s see how to create and send a simple text message (both the text content and the addresses may cont

docs.python.org

설정 환경

- 윈도우 계열 (윈도우7 / 10 에서 테스트함)

- python3

 

불필요한 import 가 많으므로 알아서 수정해서 쓸것..

예시 코드를 보면 여러 방법이 있는데 이게 젤 깔끔하게 메일이 가더라.

일부 코드는 삭제함.

 

코드

#-*- coding:utf-8 -*-
# SendMail Macro Ver 0.1 - with Py3

import smtplib, io, mimetypes, os, sys

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from string import Template
from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

my_Id = "아이디"
my_Mail_Addr = "메일주소" # 예) gmail.com
my_ID_Mail_Addr = my_Id + "@" + my_Mail_Addr
my_Pwd = "비밀번호"

my_Username = "보낼사람이름" # 이메일 앞에 이름 지정

attached_File = "첨부할파일명" # 첨부파일명
my_subject = "메일 제목" #제목

def read_template(filename):
    with io.open(filename, 'rt', encoding='utf-8') as template_file:
        template_file_content = template_file.read()
    return Template(template_file_content)

def send_MyEmail( receive_Hangul_Name, receive_Email_Id, receive_Email_Addr, mail_body ):

    s = smtplib.SMTP_SSL(host="SMTP 주소", port='465')
    s.login(my_ID_Mail_Addr, my_Pwd)

    # EmailMessage 형태
    # Ref : https://docs.python.org/3/library/email.examples.html
    msg = EmailMessage()
    msg['From'] = Address(my_Username, my_Id, my_Mail_Addr)
    msg['To'] = Address(receive_Hangul_Name, receive_Email_Id, receive_Email_Addr)
    msg['Subject'] = receive_Hangul_Name + my_subject
    asparagus_cid = make_msgid()
    msg.add_alternative(mail_body.format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
    
    ## 첨부파일
    path = os.path.join('.', attached_File)
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    with open(path, 'rb') as fp:
        msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=attached_File)
    s.send_message(msg)
    

def main():
    with open('list.txt', 'r', encoding='UTF8') as fp:
        receiver = fp.readlines()
        for line in receiver:
            receive_Hangul_Name = "보낼사람 이름"
            receive_Email_Id = "보낼사람 메일 ID"
            receive_Email_Addr = "보낼사람 메일 주소"

            # 보낼 내용은 for_send_msg.html 파일에 HTML 형태로 작성해 둘 것.

            mail_body = read_template('for_send_msg.html').substitute() # substitute 뭐하는 놈이지?
            send_MyEmail( receive_Hangul_Name, receive_Email_Id, receive_Email_Addr, mail_body )

            if os.path.isfile(for_send_msg_file):
                os.remove(for_send_msg_file)


if __name__ == '__main__':
    main()

 

Byte Stream과 같은 Hex로 구성된 ByteArray Object를 문자열로 변환할 때 한글을 포함한 특수문자를 깨짐 없이 표현하기 위해서는 UTF8로 인코딩해야 합니다.

 

구글에서 검색했을 때 대부분의 사람들은 ASCII로 인코딩하는 예시 코드를 공유해주고 있어서, 3~4시간 정도를 낭비했습니다. ㅠㅠ

정확히 변환되는 코드를 찾아서 기록해두었습니다.

 

아래의 코드 예시를 이용하여 변환하세요.

 

[Code] 

    function UTF8stringFromByteArray(data)
    {
        const extraByteMap = [ 1, 1, 1, 1, 2, 2, 3, 0 ];
        var count = data.length;
        var str = "";
        for (var index = 0;index < count;)
        {
            var ch = data[index++];
            if (ch & 0x80)
            {
                var extra = extraByteMap[(ch >> 3) & 0x07];
                if (!(ch & 0x40) || !extra || ((index + extra) > count))
                    return null;
                ch = ch & (0x3F >> extra);
                for (;extra > 0;extra -= 1)
                {
                    var chx = data[index++];
                    if ((chx & 0xC0) != 0x80)
                        return null;
                    ch = (ch << 6) | (chx & 0x3F);
                }
            }
            str += String.fromCharCode(ch);
        }
        return str;
    }

출처 : https://weblog.rogueamoeba.com/2017/02/27/javascript-correctly-converting-a-byte-array-to-a-utf-8-string/

 

 

 

 

 

조건문 사용시 대괄호 안에 띄어쓰기가 꼭 필요합니다.

 

기본적인 문법

if [[ condition ]]; then
  #statements
elif [[ condition ]]; then
  #statements
else
  #statements
fi

 

첫번째 줄에는 sh 명령어가 있는 위치를 선언해주셔야 합니다.

안드로이드에서 테스트하기 때문에 /system/bin/sh로 지정하였습니다. 

 

예시

#! /system/bin/sh

nowhour=$(date +"%H")
if [[ $nowhour == "12" ]]; then
  echo "지금 시간은 12시에요"
elif [[ $nowhour == "00" ]]; then
  echo "새로운 하루가 시작했어요"
else
  echo "Dinner"
fi

'프로그래밍 > ShellScript' 카테고리의 다른 글

[ IF ] 다중 조건 처리할 때 표현방식  (0) 2023.07.27
디렉터리 존재여부 확인  (0) 2019.04.17

조건문에서 "-d" 옵션을 이용하여 특정 디렉터리가 존재하는지 확인할 수 있습니다.

 

[Code] 

mydir="MyDir"
if [[ -d "$mydir" ]]; then
    echo "Exists"
fi
if [[ ! -d "$mydir" ]]; then
    echo "Not Exists"
fi​

 

 

 

'프로그래밍 > ShellScript' 카테고리의 다른 글

[ IF ] 다중 조건 처리할 때 표현방식  (0) 2023.07.27
[shell script] if  (0) 2019.04.20

+ Recent posts